我使用NSLayout锚创建了一个高度为100的视图。当我尝试更新按钮单击时,它不起作用。

我已经尝试了下面的代码,但是没有用。

class ViewController: UIViewController {
    @IBOutlet weak var button: UIButton!

    let viewAnimate = UIView()
    var isHidden = false

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(viewAnimate)

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        viewAnimate.translatesAutoresizingMaskIntoConstraints = false
        viewAnimate.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8).isActive = true
        viewAnimate.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8).isActive = true
        viewAnimate.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true
        viewAnimate.heightAnchor.constraint(equalToConstant: 100).isActive = true
        viewAnimate.backgroundColor = UIColor.red
    }

    @IBAction func show() {

        if !isHidden {
            viewAnimate.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 200).isActive = true
            button.setTitle("Show", for: .normal)
        } else {
            button.setTitle("Hide", for: .normal)
            viewAnimate.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true
        }

        UIView.animate(withDuration: 1) {
            self.viewAnimate.layoutIfNeeded()
        }

        isHidden = !isHidden
    }
}

视图应根据高度限制更改高度

最佳答案

您的当前代码会产生冲突,因为像viewAnimate.topAnchor.constraint(equalTo:这样的每一行都会添加一个新约束,创建一个变量

var topCon:NSLayoutConstraint!
topCon = viewAnimate.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100)
topCon.isActive = true
@IBAction func show() {

        if !isHidden {
            topCon.constant = 200
            button.setTitle("Show", for: .normal)
        } else {
            button.setTitle("Hide", for: .normal)
            topCon.constant = 100
        }

        UIView.animate(withDuration: 1) {
            self.view.layoutIfNeeded()
        }

        isHidden = !isHidden
}

关于ios - 更新布局 anchor 无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57868174/

10-12 12:47
查看更多