How to change height of UIView that already has height anchor?

前端 未结 5 403

If I have this for a child view controller:

autoCompleteViewController.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.act         


        
5条回答
  •  执笔经年
    2021-01-13 13:43

    You can do something like this:

    class ViewController: UIViewController {
    
        var constantValue: CGFloat = 44
    
        let childView: UIView = {
            let view = UIView()
            view.backgroundColor = .red
            return view
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            view.addSubview(childView)
    
            childView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                childView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
                childView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
                childView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
                childView.heightAnchor.constraint(equalToConstant: constantValue)
                ])
    
        }
    
        @IBAction func changeHeight(_ sender: UIButton) {
    
            constantValue = 100
    
            UIView.animate(withDuration: 0.5, animations: {
    
                if let constraint = (self.childView.constraints.filter{$0.firstAttribute == .height}.first) {
    
                    constraint.constant = self.constantValue
                }
    
                self.view.layoutIfNeeded()
            })
        }
    
    }
    

提交回复
热议问题