gpt4 book ai didi

ios - 如何将 viewWillTransition 保留到一个 View Controller 而不是全部?

转载 作者:可可西里 更新时间:2023-11-01 00:21:03 30 4
gpt4 key购买 nike

这是我如何重写我的 View Controller ,但是,如果有另一种更好的方法来做到这一点,那么我的第二个 View Controller 不符合重写请指导我,任何建议都会很好.

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
}

最佳答案

虽然您已经找到解决问题的方法,但我想我会提供一种更简单的方法来处理它。另一个好处是它不会那么脆弱,因为无论您的 Controller 中有什么 View ,它都可以工作。

首先,一些上下文部分基于已经包含在 Malik 的回答的评论中的信息:正如 Malik 指出的,“viewWillTransition”方法只会在包含它的 View Controller 中执行。但是由于您使用的是标签栏 Controller ,因此即使您在不同的标签页上,与标签栏关联的每个 Controller 仍然存在。因此,即使当您旋转设备时用户位于不同的选项卡 Controller 上,“viewWillTransition”方法仍会在具有该方法的 Controller 中被调用。那么,如果您希望该方法中的代码仅在用户当前位于该选项卡上时才执行怎么办?

这是一个更简单的解决方案:如果您希望仅当用户位于该 Controller 的选项卡上时才调用当前位于“viewWillTransition”中的代码,您可以在该代码之前添加一个 guard 语句检查“tabBarController.selectedIndex”的当前值。 “selectedIndex”值告诉您当前选择和可见的选项卡 Controller 。

例如,假设“viewWillTransition”位于索引为 0 的选项卡 Controller 中。您可以包含一个 guard 语句来检查 selectedIndex 是否为 0,如果不是,则返回。如果用户当前不在选项卡 0 上,这将阻止执行方法中的其余代码。如果用户在索引为 1 的选项卡上并旋转设备,尽管仍会调用“viewWillTransition”在 Controller 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
}

希望这对您或其他人有帮助!

关于ios - 如何将 viewWillTransition 保留到一个 View Controller 而不是全部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44236928/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com