Moh*_*hah 2 xcode overriding ios swift
这就是我重写视图控制器的方式,但是,如果还有另一种更好的方法可以做到这一点,并且使我的第二个视图控制器与重写不符,请直接指导我,任何建议都可以。
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
let orient = UIApplication.shared.statusBarOrientation
switch orient {
case .portrait:
print("Portrait")
self.applyPortraitConstraint()
break
// Do something
default:
print("LandScape")
// Do something else
self.applyLandScapeConstraint()
break
}
}, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
print("rotation completed")
})
super.viewWillTransition(to: size, with: coordinator)
}
func applyPortraitConstraint(){
stackView.axis = .vertical
stackView.distribution = .fill
}
func applyLandScapeConstraint(){
stackView.axis = .horizontal
stackView.distribution = .fillEqually
}
Run Code Online (Sandbox Code Playgroud)
小智 5
尽管您找到了解决该问题的方法,但我认为我会提供一种更简单的方法来解决该问题。另一个好处是,无论控制器中的视图是什么,它都可以工作,因此不那么脆弱。
首先,一些上下文部分基于已经包含在Malik答案注释中的信息:正如Malik指出的那样,“ viewWillTransition”方法将仅在包含它的视图控制器中执行。但是,由于您使用的是选项卡栏控制器,因此即使您位于其他选项卡上,与该选项卡栏关联的每个控制器仍然存在。因此,即使用户在旋转设备时位于不同的选项卡控制器上,在具有该方法的控制器中仍将调用“ viewWillTransition”方法。因此,如果您希望仅当用户当前在该选项卡上时才执行该方法中的代码,该怎么办?
这是一个更简单的解决方案:如果只希望在用户位于该控制器的选项卡上时才调用“ viewWillTransition”中当前的代码,则可以在该代码之前添加一个保护语句,以检查“ tabBarController.selectedIndex”的当前值。 。“ selectedIndex”值告诉您当前已选择并可见的选项卡控制器。
例如,假设“ viewWillTransition”位于索引为0的选项卡控制器中。您可以包含一个保护语句,该语句检查selectedIndex为0,否则返回。如果用户当前不在选项卡0上,这将防止执行该方法中的其余代码。如果用户位于索引为1的选项卡上并旋转设备,尽管仍将调用“ viewWillTransition”在控制器0中,guard语句将阻止其余代码执行。
这是代码:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard tabBarController?.selectedIndex == 0 else { return }
//Include the rest of your code here
}
Run Code Online (Sandbox Code Playgroud)
希望这对您或其他人有帮助!
| 归档时间: |
|
| 查看次数: |
1366 次 |
| 最近记录: |