Search code examples
iosautolayout

Where is the best place to add constraints to custom tableviewcells?


I know the best place to add constraints is viewDidLoad, but for a custom view, especially for custom cells, I'd like to hide all these layout details to itself, without exposed to its controller. And I don't want VC to send message to its view, because it contributes a little to coupling, which I hate most.So where should I add constraints, in the init method or layoutSubview, or something else?


Solution

  • If not using storyboards, I would say the best place to add your constraints is in the init method of UITableViewCell:

    class CustomTableViewCell : UITableViewCell {
    
        lazy var subview: UIView = {
            let view = UIView()
            view.backgroundColor = .orange
            view.translatesAutoresizingMaskIntoConstraints = false
            return view
        }()
    
        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            contentView.addSubview(subview)
            NSLayoutConstraint.activate([
                subview.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
                subview.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
                subview.topAnchor.constraint(equalTo: contentView.topAnchor),
                subview.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
                subview.heightAnchor.constraint(equalToConstant: 230.0)
            ])
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }