使用约束动画生成的视图

问题描述 投票:0回答:1

我在UIStackView中放置了一些动态生成的视图。我想点击任何红色视图,并使用宽度锚约束将其设置为200。动态生成视图并放置在UIStackview中是非常重要的。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var arrangedSubviews = [AnyObject]()
        for _ in 0...5 {
                let redView = UIView()
                redView.backgroundColor = .red
                redView.translatesAutoresizingMaskIntoConstraints = false
                redView.widthAnchor.constraint(equalToConstant: 50).isActive = true
                redView.layer.borderWidth = 1
                redView.layer.borderColor = UIColor.white.cgColor
                arrangedSubviews.append(redView)
        }

        let stackView = UIStackView(arrangedSubviews: arrangedSubviews as! [UIView])
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.heightAnchor.constraint(equalToConstant: view.frame.height).isActive = true
        view.addSubview(stackView)

        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
    }

    @objc func handleTap(gesture: UITapGestureRecognizer){
        let location = gesture.location(in: view)
        print(location)
        for firstViews in view.subviews {
            for secondViews in firstViews.subviews {
                if secondViews.frame.contains(location){
                    secondViews.widthAnchor.constraint(equalToConstant: 200)
                    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                        self.view.layoutIfNeeded()
                    }, completion: nil)
                }
            }
        }
    }
}
ios swift animation constraints uistackview
1个回答
0
投票

改变这一点

secondViews.widthAnchor.constraint(equalToConstant: 200)

进入这个

let widthConstraint = secondViews.constraints.first(where: { $0.firstAttribute == .width })
widthConstraint?.constant = 200

还有这个

self.view.layoutIfNeeded()

进入这个

firstViews.layoutIfNeeded()
© www.soinside.com 2019 - 2024. All rights reserved.