How to create a custom UITableViewCell programmatically using AutoLayout How to create a custom UITableViewCell programmatically using AutoLayout ios ios

How to create a custom UITableViewCell programmatically using AutoLayout


There are several things wrong with your code. First, I think you'll find, if you do some logging, that updateConstraints is never called. I would put all the code in the init method. Also, there are several things wrong in your constraints. The constraint where you set the height to 44 is not needed since you already have the labels pinned to the to and bottom of the cell. I don't know what you're trying to do with that last one, it looks like that would make the nameLabel 1 point wide. Also, you shouldn't set the translatesAutoresizingMaskIntoConstraints to NO for the content view, that causes weird effects. So this is the code I think you want:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];    if (self) {        reuseID = reuseIdentifier;        nameLabel = [[UILabel alloc] init];        [nameLabel setTextColor:[UIColor blackColor]];        [nameLabel setBackgroundColor:[UIColor colorWithHue:32 saturation:100 brightness:63 alpha:1]];        [nameLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];        [nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];        [self.contentView addSubview:nameLabel];        mainLabel = [[UILabel alloc] init];        [mainLabel setTextColor:[UIColor blackColor]];        [mainLabel setBackgroundColor:[UIColor colorWithHue:66 saturation:100 brightness:63 alpha:1]];        [mainLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];        [mainLabel setTranslatesAutoresizingMaskIntoConstraints:NO];        [self.contentView addSubview:mainLabel];        NSDictionary *views = NSDictionaryOfVariableBindings(nameLabel, mainLabel);        if (reuseID == kCellIDTitle) {            NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"                                                                           options: 0                                                                           metrics:nil                                                                             views:views];            [self.contentView addConstraints:constraints];            constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel]|"                                                                  options: 0                                                                  metrics:nil                                                                    views:views];            [self.contentView addConstraints:constraints];        }        if (reuseID == kCellIDTitleMain) {            NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"                                                                           options:0                                                                           metrics:nil                                                                             views:views];            [self.contentView addConstraints:constraints];            constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[mainLabel]|"                                                                  options: 0                                                                  metrics:nil                                                                    views:views];            [self.contentView addConstraints:constraints];            constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel][mainLabel(==nameLabel)]|"                                                                  options: 0                                                                  metrics:nil                                                                    views:views];            [self.contentView addConstraints:constraints];        }    }    return self;}


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.