Swift 自定义 tableViewCell

卫骏
2023-12-01

创建类 CustomTableViewCell:

import UIKit

class CustomTableViewCell: UITableViewCell {

    lazy var backView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y:0, width: self.frame.width, height: 50))
        return view
    }()
    
    lazy var settingImage:UIImageView = {
        let imageView = UIImageView(frame: CGRect(x: 15, y: 10, width: 30, height: 30))
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    lazy var lbl:UILabel = {
        let lbl = UILabel(frame: CGRect(x: 60, y: 10, width: 30, height: 30))
        return lbl
    }()
    
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        addSubview(backView)
        backView.addSubview(settingImage)
        backView.addSubview(lbl)
    }

}

使用方法:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for: indexPath) as? CustomTableViewCell else {fatalError("Unable to deque cell")}
        cell.lbl.text = "test"
        cell.settingImage.image = UIImage(named: "imgName")
        return cell
    }
 类似资料: