我嘗試刪除約束。我希望對肖像和風景有不同的限制。如果我將方向更改爲縱向,則我調用函數setupConstrainsInPortrait,反之亦然。我有兩個功能。刪除約束iOS
此功能設置縱向模式。
func setupConstrainsInPortrait() {
view.addSubview(myView)
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
myView.heightAnchor.constraint(equalToConstant: 300).isActive = true
myView.widthAnchor.constraint(equalToConstant: view.frame.size.width).isActive = true
view.addSubview(switchKmM)
switchKmM.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
switchKmM.topAnchor.constraint(equalTo: myView.bottomAnchor, constant: 10).isActive = true
switchKmM.heightAnchor.constraint(equalToConstant: 50).isActive = true
switchKmM.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
view.addSubview(speedLbl)
speedLbl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
speedLbl.topAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
speedLbl.heightAnchor.constraint(equalToConstant: 50).isActive = true
speedLbl.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
}
此功能設置橫向模式。
func setupConstrainsInLandScape() {
view.addSubview(myView)
myView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
myView.heightAnchor.constraint(equalToConstant: 300).isActive = true
myView.widthAnchor.constraint(equalToConstant: 150).isActive = true
view.addSubview(switchKmM)
switchKmM.leftAnchor.constraint(equalTo: myView.rightAnchor, constant: 30).isActive = true
switchKmM.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
switchKmM.heightAnchor.constraint(equalToConstant: 50).isActive = true
switchKmM.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
}
我viewWillTransition
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
print("landscape!")
view.backgroundColor = .green
setupConstrainsInLandScape()
self.viewWillLayoutSubviews()
}
else {
print("portrét")
view.backgroundColor = .white
setupConstrainsInPortrait()
self.viewWillLayoutSubviews()
}
super.viewWillTransition(to: size, with: coordinator)
}
的問題是使用這些功能,即限制(從縱向功能)以橫向模式不會被刪除
我希望有人能幫助我。 ..謝謝
什麼問題?給出理想的結果與實際結果。 – matt
問題是,沒有刪除橫向模式下的約束(來自縱向功能) –
「橫向模式下的約束(來自縱向功能)不會被刪除」不出現意外。我沒有看到任何會刪除它們的代碼。你所做的只是說'isActive = true'。從來沒有你說'isActive = false'。所以你只是不斷添加和添加約束而不刪除任何。在那種情況下,你期望什麼? – matt