2016-12-25 53 views
3

我想在手機方向更改時重新計算高度約束。我正在使用函數uninstall()install()來實現此目的。但是,它不能按需要工作。我是否錯誤地使用它們?重新計算方向變化時的SnapKit約束

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() 
    } 
} 

回答

2

如果您希望您的tableView有在景觀不同的高度和縱向可以使用2點不同的方法:

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

在這裏,你只需要在約束上調用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() 
    } 
}