无法将类型'()'的值转换为预期的元素类型'NSLayoutConstraint'

时间:2019-06-10 18:15:48

标签: swift

我遵循了有关在Swift中创建下拉列表的YouTube教程。 我遇到了无法修复的错误,我在Stackoverflow和Google的搜索结果中查看了此内容,但对我没有任何帮助。 这是我遇到的问题:

  

无法将类型'()'的值转换为预期的元素类型'NSLayoutConstraint'

这是代码:

class Dropdown: UIButton, DropDownProtocol {
    var dropView = DropDownView()
    var height = NSLayoutConstraint()
    var isOpen = false

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.appBlack
        dropView = DropDownView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        dropView.translatesAutoresizingMaskIntoConstraints = false
        dropView.delegate = self
    }

    override func didMoveToSuperview() {
        self.superview?.addSubview(dropView)
        self.superview?.bringSubviewToFront(dropView) //Needed?

        NSLayoutConstraint.activate([
            dropView.topAnchor.constraint(equalTo: self.bottomAnchor),
            dropView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
            dropView.widthAnchor.constraint(equalTo: self.widthAnchor),
            height = (dropView.heightAnchor.constraint(equalToConstant: 0)) <--- problem occurs here
        ])
    }
}

1 个答案:

答案 0 :(得分:2)

请勿在对height的调用中为activate分配值。

重构一下:

override func didMoveToSuperview() {
    self.superview?.addSubview(dropView)
    self.superview?.bringSubviewToFront(dropView) //Needed?

    height = dropView.heightAnchor.constraint(equalToConstant: 0)

    NSLayoutConstraint.activate([
        dropView.topAnchor.constraint(equalTo: self.bottomAnchor),
        dropView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        dropView.widthAnchor.constraint(equalTo: self.widthAnchor),
        height
    ])
}