我想在手机方向改变时重新计算高度约束。我使用的功能uninstall(),并install()做到这一点。但是,它没有按预期工作。我是否错误地使用了它们?
class ActionOverlayViewController: UIViewController {
private var tableView = UITableView()
private var heightConstraint: Constraint?
override func viewDidLoad() {
super.viewDidLoad()
tableView.snp_makeConstraints { make in
self.heightConstraint = make.height.lessThanOrEqualTo(UIScreen.mainScreen().bounds.size.height).priorityHigh().constraint
make.height.equalTo(242).priorityLow()
}
}
override func updateViewConstraints() {
tableView.snp_updateConstraints { make in
self.heightConstraint.uninstall()
self.heightConstraint.install()
}
super.updateViewConstraints()
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateViewConstraints()
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想让tableView横向和纵向具有不同的高度,您可以使用两种不同的方法:
1. 横向高度应为 200,纵向高度应为 400:
class ViewController: UIViewController {
let tableView = UITableView()
var heightConstraint: Constraint?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(0)
self.heightConstraint = make.height.equalTo(0).constraint
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
let height = UIDevice.current.orientation.isLandscape ? 200 : 400
heightConstraint?.update(offset: height)
}
}
Run Code Online (Sandbox Code Playgroud)
在这里你只需要调用update(offset:)约束即可。无需经过updateViewConstraints()。如果你有静态高度,这很有效。
2. 纵向高度应为屏幕高度的一半,横向高度应为全屏:
在这里您必须更新整个约束,因为您不使用静态高度。因此,您不需要保留对约束的引用,但您必须执行以下操作updateViewConstraint():
class ViewController: UIViewController {
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
}
override func updateViewConstraints() {
super.updateViewConstraints()
tableView.snp.remakeConstraints { (make) in
make.top.left.right.equalTo(0)
if UIDevice.current.orientation.isLandscape {
make.bottom.equalTo(0)
} else {
make.bottom.equalTo(view.snp.centerY)
}
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
view.setNeedsUpdateConstraints()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1438 次 |
| 最近记录: |