使用约束对动态生成的视图进行动画处理

时间:2019-02-26 06:52:05

标签: ios swift animation constraints uistackview

我在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)
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

更改此内容

secondViews.widthAnchor.constraint(equalToConstant: 200)

进入此

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

还有这个

self.view.layoutIfNeeded()

进入此

firstViews.layoutIfNeeded()