Swift 3.0中UITableViewCell纯代码自定义

在swift 3.0中纯代码自定义UITableViewCell的使用,
自定义cell:

class CustomCell: UITableViewCell {

    var titleLabel:UILabel?
    var picImgView:UIImageView?

    required init?(coder aDecoder:NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(style:UITableViewCellStyle, reuseIdentifier:String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setUpUI();
    }

    func setUpUI() {

        self.titleLabel = UILabel.init()
        self.titleLabel?.backgroundColor = UIColor.clear;
        self.titleLabel?.frame = CGRect(x:0, y:0, width:100, height:30)
        self.titleLabel?.text = "Title"
        self.titleLabel?.textColor = UIColor.black
        self.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        self.titleLabel?.textAlignment = NSTextAlignment.center
        self.addSubview(self.titleLabel!)

        self.picImgView = UIImageView()
        self.picImgView?.frame = CGRect(x:110, y:50, width:50, height:50)
        self.picImgView?.backgroundColor = UIColor.lightGray
        self.picImgView?.image = UIImage.init(named: "a")
        self.addSubview(self.picImgView!)

    }

ViewController中的主要代码,实例化UITableView,在这里,CGRect的用法和Swift2.0的有所不同了

func setLayout() {

        mainTable = UITableView.init(frame: CGRect(x: 0, y: 20, width:self.view.frame.size.width, height:self.view.frame.size.height - 20), style: UITableViewStyle.plain)
        mainTable?.backgroundColor = UIColor.white
        mainTable?.delegate = self;
        mainTable?.dataSource = self;
        self.view.addSubview(mainTable!)
    }

UITableView的行数,行高,Section部分的代码就不展示了,cellForRowIndexPath的方法和Object-C以及Swift 2.0的有所不同,所以在这里给出,供参考
“`
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let reuStr:String = "ABC" 
    if cell == nil {         
    cell=CustomCell(style:UITableViewCellStyle.default, reuseIdentifier: reuStr)
    }
    cell.titleLabel?.text = "OOKK"
    tableView.separatorStyle = UITableViewCellSeparatorStyle.none;
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    return cell
}

你可能感兴趣的:(Swift)