运行 加载视图控制器之前的 tabBarItem 代码
Running tabBarItem code before view controller loads
我有一个标签栏应用程序,我将以下代码放入我的视图控制器中:
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
}
这会更改我的标签栏项目标题的偏移量。在风景中,偏移量会自动反转,所以我必须手动完成。这有效,但只有当您实际单击选项卡栏项目并加载视图控制器时才有效。
我想在开始时加载此代码,因此它会在您启动应用程序时(在加载视图控制器之前)更改偏移量。这里有一些图片来描述我所说的:
当您第一次启动应用程序时,这是第一个视图控制器,因此它会加载该代码并更改位置:
如果您点击第二个项目,第二个视图控制器会加载并改变位置。
我需要为每个标签栏项目加载这段代码,所以它从一开始看起来是这样的:
在 viewWillAppear()
函数中尝试 运行 此代码。
您应该子类化 UITabBarController
并在控制器加载后执行更改标题位置调整的代码 (viewDidLoad
) 并且每次视图 size/orientation 更改时 (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 { [=10=].titlePositionAdjustment = UIOffset(horizontal: 0, vertical: isLandscape ? 0 : -17) }
}
}
我有一个标签栏应用程序,我将以下代码放入我的视图控制器中:
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
}
这会更改我的标签栏项目标题的偏移量。在风景中,偏移量会自动反转,所以我必须手动完成。这有效,但只有当您实际单击选项卡栏项目并加载视图控制器时才有效。
我想在开始时加载此代码,因此它会在您启动应用程序时(在加载视图控制器之前)更改偏移量。这里有一些图片来描述我所说的:
当您第一次启动应用程序时,这是第一个视图控制器,因此它会加载该代码并更改位置:
如果您点击第二个项目,第二个视图控制器会加载并改变位置。
我需要为每个标签栏项目加载这段代码,所以它从一开始看起来是这样的:
在 viewWillAppear()
函数中尝试 运行 此代码。
您应该子类化 UITabBarController
并在控制器加载后执行更改标题位置调整的代码 (viewDidLoad
) 并且每次视图 size/orientation 更改时 (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 { [=10=].titlePositionAdjustment = UIOffset(horizontal: 0, vertical: isLandscape ? 0 : -17) }
}
}