我需要你的帮助,因为我不明白我的自动约束是怎么回事。我的开关的限制使应用程序崩溃。当我把它们取下来的时候,效果很好。这是我得到的错误信息:无法解释'|'字符,因为相关视图没有父视图H: | -100 - (v0 (35) |
谢谢你的帮助
下面是我的代码:class selectionCustomCell: UITableViewCell{
var label: UILabel = {
let attribution = UILabel()
attribution.text = "Nom du label"
attribution.textColor = UIColor(r: 0, g: 185, b: 255)
attribution.lineBreakMode = NSLineBreakMode.ByWordWrapping
attribution.numberOfLines = 0
attribution.translatesAutoresizingMaskIntoConstraints = false
return attribution
}()
var switchElement: UISwitch{
let sL = UISwitch()
sL.setOn(true, animated: true)
sL.onTintColor = UIColor(r: 0, g: 185, b: 255)
sL.tintColor = UIColor(r: 0, g: 185, b: 255)
sL.translatesAutoresizingMaskIntoConstraints = false
return sL
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Default, reuseIdentifier: reuseIdentifier)
addSubview(switchElement)
addSubview(label)
setupViews()
}
func setupViews(){
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": label]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": label]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-100-[v0(35)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": switchElement]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[v0(35)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": switchElement]))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
注意label
和switchView
的声明方式的区别:label
初始化为闭包的输出,它在第一次被引用时执行。switchView
是一个计算的属性,每次引用它都会调用getter,这意味着您在-setupViews
中引用的版本与之前调用-addSubview
的版本不一样。由于它们不属于视图层次结构,因此可视格式无效。
如果你使switchView
的声明匹配label
的声明,你的代码应该像预期的那样工作:
var switchElement: UISwitch = { // note the assignment operator here
let sL = UISwitch()
// ...
return sL
}() // note the invocation of the block here