我有一个标签栏应用程序,我将以下代码放在我的 View Controller 中:
let orientation = UIDevice.current.orientation
if orientation == .portrait {
self.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -17.0)
} else if orientation == .landscapeLeft || orientation == .landscapeRight {
self.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 0.0) // updating the title positon
}
这会更改我的标签栏项目标题的偏移量。在风景中,偏移量会自动反转,所以我必须手动完成。这有效,但只有当您实际单击标签栏项目并加载 View Controller 时才有效。
我想在开始时加载此代码,因此它会在您启动应用程序时(在 View Controller 加载之前)更改偏移量。这里有一些图片来描述我所说的:
当您第一次启动应用程序时,这是第一个 View Controller ,因此它会加载该代码并更改位置:
如果你点击第二个项目,第二个 View Controller 加载并且它也会改变位置。
我需要为每个标签栏项目加载这段代码,所以它从一开始看起来是这样的:
最佳答案
您应该子类化 UITabBarController
并在 Controller 加载后执行更改标题位置调整的代码 (viewDidLoad
) 以及每次 View 大小/方向更改时 (viewWillTransition
).
class CustomTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
tabBarItemsUI()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { [weak self] context in
self?.tabBarItemsUI()
})
}
fileprivate func tabBarItemsUI() {
let isLandscape = [.landscapeLeft, .landscapeRight].contains(UIDevice.current.orientation)
tabBar.items?.forEach { $0.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: isLandscape ? 0 : -17) }
}
}
关于ios - 在 View Controller 加载之前运行 tabBarItem 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49868269/