How to create a custom UITableViewCell programmatically using AutoLayout

后端 未结 2 1267
轮回少年
轮回少年 2020-12-12 18:17

I\'m trying to implement a UITableView that will behave similarly to the timeline of a twitter client. Right now I\'m simply attempting to get two labels inside a UITableVie

2条回答
  •  Happy的楠姐
    2020-12-12 18:52

    You can create UITableViewCell programatically in swift 4 using auto-layout like below. It's not exactly the solution of your above problem as you specified in question, It's more generic implementation how to create Tableview cell programatically in swift using auto-layout :

    class ViewController: UITableViewController {
    
    override func viewDidLoad() {
       super.viewDidLoad()
       tableView.register(CustomCell2.self, forCellReuseIdentifier: "cell")
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
      return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 2
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? CustomCell2 else { return UITableViewCell() }
      cell.model = CellModel(labelString: "set constriant by code")
      return cell
      }  
      }
    

    Define Model :

    struct CellModel {
      let labelString : String
     }
    

    Define Custom Cell :

    class CustomCell2 : UITableViewCell {
    private let label : UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false // enable auto layout
        label.backgroundColor = .green // to visualize the background of label
        label.textAlignment = .center // center text alignment
        return label
    }()
    
    private func addLabel() {
        addSubview(label)
        NSLayoutConstraint.activate([
            // label width is 70% of cell width 
            label.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.7),
            // label is horizontally center of cell
            label.centerXAnchor.constraint(equalTo: centerXAnchor)
        ])
    }
    
    var model : CellModel? {
        didSet {
            label.text = model?.labelString ?? ""
        }
    }
    
    // Init 
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addLabel()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    }
    

    This is the output of above program.

    This is the actual project, you can check out.

提交回复
热议问题