【问题标题】:Animate dynamically generated views using constraints使用约束对动态生成的视图进行动画处理
【发布时间】:2019-02-26 06:52:04
【问题描述】:

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

【问题讨论】:

  • 为什么要在 self.view 中添加点击手势?给redview添加手势或者在redview中添加一个按钮

标签: ios swift animation constraints uistackview


【解决方案1】:

改变这个

secondViews.widthAnchor.constraint(equalToConstant: 200)

进入这个

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

还有这个

self.view.layoutIfNeeded()

进入这个

firstViews.layoutIfNeeded()

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 1970-01-01
    • 2019-09-10
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多