【发布时间】: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