Swift學習筆記三 自定義TableViewCell
阿新 • • 發佈:2018-12-21
學了tableView的用法,不得不說自定義TableViewCell,畢竟靠系統的cell遠遠滿足不了產品需求
所以在上個筆記的基礎上 自定義了一個cell
直接上程式碼
override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style:style,reuseIdentifier:reuseIdentifier) setupBasic() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
相信很眼熟,不多說 繼續
//用 public 這樣外界控制器就能呼叫賦值 fileprivate 是私有 ,外界不能呼叫 public var hintLabel:UILabel = { let hintLabel = UILabel() hintLabel.font = UIFont.systemFont(ofSize: 15) hintLabel.textAlignment = .center hintLabel.textColor = UIColor.green return hintLabel }()
初始化要用的控制元件,我這裡只創了一個label public和fileprivate自己看著來
接下來是佈局
extension CustomTableViewCell{ fileprivate func setupBasic(){ //新增到self.contentView上 self.contentView.addSubview(hintLabel) } // layoutSubviews 和OC一樣 addSubView 方法自動呼叫 override func layoutSubviews() { //這裡使用了OC程式碼的SDAutoLayOut 如何在swift中使用OC程式碼,請小夥伴自行百度 _ = hintLabel.sd_layout() .centerYEqualToView(self.contentView)? .centerXEqualToView(self.contentView)? .widthIs(60)?.heightIs(40); } }
這裡用到了SDAutoLayOut,是OC程式碼,不過swift和OC是可以橋接的,至於如何橋接,請大家移步百度
在VC裡,和OC一樣,更改註冊cell時的Class 為 CustomTableViewCell cellForRow處也是一樣
執行效果如下
完整cell程式碼
import UIKit
class CustomTableViewCell: UITableViewCell {
//用 public 這樣外界控制器就能呼叫賦值 fileprivate 是私有 ,外界不能呼叫
public var hintLabel:UILabel = {
let hintLabel = UILabel()
hintLabel.font = UIFont.systemFont(ofSize: 15)
hintLabel.textAlignment = .center
hintLabel.textColor = UIColor.green
return hintLabel
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style:style,reuseIdentifier:reuseIdentifier)
setupBasic()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CustomTableViewCell{
fileprivate func setupBasic(){
//新增到self.contentView上
self.contentView.addSubview(hintLabel)
}
// layoutSubviews 和OC一樣 addSubView 方法自動呼叫
override func layoutSubviews() {
//這裡使用了OC程式碼的SDAutoLayOut 如何在swift中使用OC程式碼,請小夥伴自行百度
_ = hintLabel.sd_layout()
.centerYEqualToView(self.contentView)?
.centerXEqualToView(self.contentView)?
.widthIs(60)?.heightIs(40);
}
}