swift 4自定义UITableCell的方法示例

2020-01-09 00:16:15于丽

前言

本文主要给大家介绍了关于swift 4自定义UITableCell的相关内容,分享出来供大家参考学习价值,下面话不多说了,来一起看看详细的介绍吧

直接上图

swift4,UITableCell

新建MenuCell

创建一个类 MenuCell 继承 UITableViewCell 添加两个要实现的方法


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

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

初始化组件

把tableCell里要显示的组件都初始化好,我这里就只有两个组件


class MenuCell: UITableViewCell {
 var icon = UIImageView()
 var 
 lazy var box = UIView()
 
 override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
 super.init(style: style, reuseIdentifier: reuseIdentifier)
 
 box.addSubview(icon)
 box.addSubview(title)
 
 self.addSubview(box)
 }
}

组件加进去了,接下来就是布局了,Github上有个star数很高的布局库,用pod安装就可以用了,地址:https://www.easck.com// 设置icon组件距离box组件左,上各10个距离单位(不太清楚是不是像素),偏移12个距离单位 make.left.top.equalTo(10).offset(12) // 设置icon的宽高各20个单位 make.width.height.equalTo(20) } title.snp.makeConstraints { (make) in // 设置title组件位置从icon组件的右边开始算起,再偏移10个单位 make.left.equalTo(self.icon.snp.right).offset(10) // 设置title距离上面高度跟icon一样 make.top.equalTo(self.icon) } }