将约束添加到自定义tableviewcell的最佳位置在哪里? [英] Where is the best place to add constraints to custom tableviewcells?
问题描述
我知道添加约束的最佳位置是viewDidLoad,但是对于自定义视图(尤其是自定义单元格),我想将所有这些布局详细信息隐藏起来而不暴露给它的控制器.而且我不希望VC向其视图发送消息,因为它对耦合最有帮助,这是我最讨厌的.因此,我应该在init方法或layoutSubview或其他内容中添加约束?
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?
推荐答案
如果不使用情节提要,那么添加约束的最佳位置是UITableViewCell
的init方法:
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")
}
}
这篇关于将约束添加到自定义tableviewcell的最佳位置在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!