向自定义 UIButton 添加约束不起作用

Adding constraints to a custom UIButton doesn't work

您好,我有以下代码:

class MyController {    
    override func viewDidLoad() {
        self.addButtons()

        super.viewDidLoad()
    }

    func addButtons() {
        let cancelButton = UIButton(type: .custom)
        let validateButton = UIButton(type: .custom)

        cancelButton.setImage(UIImage(named: "cancel_icon"), for: .normal)
        validateButton.setImage(UIImage(named: "validate_icon"), for: .normal)

        cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        validateButton.addTarget(self, action: #selector(validateAction), for: .touchUpInside)

        cancelButton.translatesAutoresizingMaskIntoConstraints = false
        validateButton.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(cancelButton)
        self.view.addSubview(validateButton)

        let leftCancel = NSLayoutConstraint(item: cancelButton, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 16)
        let bottomCancel = NSLayoutConstraint(item: cancelButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 20)
        let widthCancel = NSLayoutConstraint(item: cancelButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
        let heightCancel = NSLayoutConstraint(item: cancelButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
        let rightValidate = NSLayoutConstraint(item: validateButton, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 16)
        let bottomValidate = NSLayoutConstraint(item: validateButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 20)
        let widthValidate = NSLayoutConstraint(item: validateButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
        let heightValidate = NSLayoutConstraint(item: validateButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
        NSLayoutConstraint.activate([leftCancel, bottomCancel, rightValidate, bottomValidate, widthCancel, heightCancel, widthValidate, heightValidate])

        self.view.layoutIfNeeded()
    }

    func cancelAction() {
        self.dismiss(animated: true, completion: nil)
    }

    func validateAction() {
        self.dismiss(animated: true, completion: nil)
    }
}

所以基本上我只是添加了两个具有宽度和高度约束的按钮,我将 cancelButton 设置为左​​下角,将 validateButton 设置为右下角。

我的按钮没有出现。当我以这种方式设置按钮的框架时,它仍然有效:

cancelButton.frame = CGRect(x: 16, y: self.view.frame.height - 40, width: 20, height: 20) 
validateButton.frame = CGRect(x: self.view.frame.width - 36, y: self.view.frame.height - 40, width: 20, height: 20)

有人知道我的约束有什么问题吗? 谢谢!

看来你把这个复杂化了。 您可以使用 VisualFormat 字符串轻松实现此目的。

看这里https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html#//apple_ref/doc/uid/TP40010853-CH27-SW1

这是一个使用您的代码的示例:

func addButtons() {
    let cancelButton = UIButton(type: .custom)
    let validateButton = UIButton(type: .custom)

    cancelButton.setImage(UIImage(named: "cancel_icon"), for: .normal)
    validateButton.setImage(UIImage(named: "validate_icon"), for: .normal)

    cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
    validateButton.addTarget(self, action: #selector(validateAction), for: .touchUpInside)

    cancelButton.translatesAutoresizingMaskIntoConstraints = false
    validateButton.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(cancelButton)
    self.view.addSubview(validateButton)

    // With visual format strings
    let views = ["cancelButton" : cancelButton, "validateButton" : validateButton]

    let horizontalFormat = "|[cancelButton]-[validateButton(==cancelButton)]|"
    let verticalFormat = "V:[cancelButton]-10-|"

    let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: horizontalFormat, options:.alignAllBottom , metrics: nil, views: views)
    let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: verticalFormat, options:.alignAllBottom, metrics: nil, views: views)

    NSLayoutConstraint.activate(horizontalConstraints)
    NSLayoutConstraint.activate(verticalConstraints)

    self.view.layoutIfNeeded()
}

VisualFormat 有其用途,但也有其自身的怪癖 - 例如元素之间的灵活间距。这是没有 VisualFormat 的解决方案:

//: Playground - noun: a place where people can play

import UIKit

import PlaygroundSupport

class MyController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        self.addButtons()
    }

    func addButtons() {
        let cancelButton = UIButton(type: .custom)
        let validateButton = UIButton(type: .custom)

        cancelButton.setImage(UIImage(named: "cancel_icon"), for: .normal)
        validateButton.setImage(UIImage(named: "validate_icon"), for: .normal)

        cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        validateButton.addTarget(self, action: #selector(validateAction), for: .touchUpInside)

        cancelButton.translatesAutoresizingMaskIntoConstraints = false
        validateButton.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(cancelButton)
        self.view.addSubview(validateButton)

        validateButton.backgroundColor = UIColor.red
        cancelButton.backgroundColor = UIColor.blue

        validateButton.setTitle("V", for: UIControlState())
        cancelButton.setTitle("C", for: UIControlState())

        let leftCancel = NSLayoutConstraint(item: cancelButton, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 16)
        let bottomCancel = NSLayoutConstraint(item: cancelButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -20)
        let widthCancel = NSLayoutConstraint(item: cancelButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
        let heightCancel = NSLayoutConstraint(item: cancelButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
        let rightValidate = NSLayoutConstraint(item: validateButton, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -16)
        let bottomValidate = NSLayoutConstraint(item: validateButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -20)
        let widthValidate = NSLayoutConstraint(item: validateButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
        let heightValidate = NSLayoutConstraint(item: validateButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)

        NSLayoutConstraint.activate([leftCancel, bottomCancel, rightValidate, bottomValidate, widthCancel, heightCancel, widthValidate, heightValidate])

        self.view.layoutIfNeeded()
    }

    func cancelAction() {
        //      self.dismiss(animated: true, completion: nil)
        print("cancel")
    }

    func validateAction() {
        //      self.dismiss(animated: true, completion: nil)
        print("validate")
    }
}

var vc = MyController()
vc.view.backgroundColor = UIColor.green
vc.view.frame = CGRect(x: 0, y: 0, width: 400, height: 400)

PlaygroundPage.current.liveView = vc.view

PlaygroundPage.current.needsIndefiniteExecution = true

您应该能够 copy/paste 将其放入 Playground 页面以查看结果。请注意,我没有您的按钮图片,所以我 "V" 和 "C" 标题。

关键区别在于将“底部”和“尾随”值设置为负值 - 也就是说,您希望按钮的底部为(包含视图的底部减去 20)。同样,按钮的后缘距包含视图的后缘为 -16。