【问题标题】:Unable to interpret '|' character无法解释“|”特点
【发布时间】:2016-09-14 18:46:34
【问题描述】:

我需要你的帮助,因为我不明白我的自动约束发生了什么。我的开关的限制使应用程序崩溃。当我删除它们时,它工作得很好。 这是我收到的错误消息: 无法解释“|”字符,因为相关视图没有超级视图 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")
    }

}

【问题讨论】:

    标签: swift swift2 autolayout


    【解决方案1】:

    注意labelswitchView 声明方式的区别: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
    

    【讨论】:

    • 哇,这么简单的区别,你节省了我几个小时,谢谢!
    猜你喜欢
    • 2020-06-06
    • 2014-08-11
    • 2020-06-07
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多