我使用Stack视图来创建一种表UI,我在StackView中有6个视图0,2,4是可见的,1,3,5是隐藏的。当点击一个可见视图时,我希望"打开"一个隐藏的视图。
我有这个代码在iOS 10上工作得很好,但由于某种原因,我无法理解它在iOS 9上工作得不好。
请注意,如果我加载所有打开的视图,关闭动画将工作,但它不会打开,当设置属性为false的隐藏。
这是我的代码-
编辑经过一些调试后,看起来视图高度约束没有从隐藏中恢复,并且它的帧高度仍然是0。
import UIKit
class DeckView: UIView {
}
class ViewController: UIViewController {
var scrollView: UIScrollView!
var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: .alignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: .alignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 0
stackView.alignment = .center
stackView.distribution = .fillProportionally
stackView.axis = .vertical
scrollView.addSubview(stackView)
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
for i in 0 ..< 8 {
let view = DeckView()
view.tag = i
view.translatesAutoresizingMaskIntoConstraints = false
view.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true
view.isUserInteractionEnabled = true
if i%2 == 0 {
view.backgroundColor = UIColor.magenta
let constriant = view.heightAnchor.constraint(equalToConstant:160)
constriant.priority = 999
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.openDeck(_:))))
view.addConstraint(constriant)
} else {
view.backgroundColor = UIColor.red
let constriant = view.heightAnchor.constraint(equalToConstant:160)
constriant.priority = 999
view.addConstraint(constriant)
view.isHidden = false
}
stackView.addArrangedSubview(view)
}
}
func openDeck(_ sender:UIGestureRecognizer) {
if let view = sender.view as? DeckView,
let childView = stackView.viewWithTag(view.tag + 1) {
UIView.animate(withDuration: 0.4, animations: {
childView.isHidden = !childView.isHidden
})
}
}
}
- 保持视图的高度优先级低于1000(选择999)。
- 不设置
setHidden:true
,如果它已经隐藏(这是UIStackView的错误)
如果有人遇到这个问题。
我可以通过删除-
来解决这个问题。stackView.distribution = .fillProportionally
我不知道为什么会发生这种情况,但我发现自动布局添加了一个名为"uisv -fill-proportional"的高度约束,其常数为0,优先级高于我的高度约束。