代码:
let size = CGSize(width: tabBar.frame.width / CGFloat(TabBarItem.allValues.count),
height: tabBar.frame.height)
let image = UIImage.image(color: Color.action, size: size)
UITabBar.appearance().selectionIndicatorImage = image
在普通设备上看起来像这样:
在 iPhone X 上是这样的:
iPhone X 标签栏项目背景未对齐的原因是什么?
更新 1:
将代码更改为如下所示后,它看起来更好,但它仍然是解决方法,因为图像没有完全占据标签栏项目空间:
var image: UIImage
if DeviceInfo.is5p8Inch {
image = UIImage.image(color: Color.action, size: CGSize(width: 4, height: 4))
image = image.resizableImage(withCapInsets: UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2), resizingMode: .tile)
} else {
let size = CGSize(width: tabBar.frame.width / CGFloat(TabBarItem.allValues.count),
height: tabBar.frame.height)
image = UIImage.image(color: Color.action, size: size)
}
更新 2:
上面的代码从 viewDidLoad
调用(也尝试从 viewWillAppear
)。 UITabBarController
的子类 100% 由代码编写(未使用 Storyboard/Xib)。
更新 3:
我们还有一个自定义按钮作为 subview 添加到 UITabBar 并正确定位。只有 selectionIndicatorImage
未对齐...
更新 4:
在 viewDidAppear
而不是 viewDidLoad
或 viewWillAppear
中运行上面的原始代码会产生以下结果:
最佳答案
你只需要在延迟之后调用它,因为在你的情况下它没有得到正确的 tabBar 高度并将它设置在 self.tabBar 中,下面的代码对我有用我在 viewDidload
Async.main {
let size = CGSize(width: tabBar.frame.width / CGFloat(TabBarItem.allValues.count),
height: tabBar.frame.height)
let image = UIImage.image(color: Color.action, size: size)
UITabBar.appearance().selectionIndicatorImage = image
self.tabBar.selectionIndicatorImage = image // this will change color and height of current tabBar
}
关于ios - UITabBar.appearance().selectionIndicatorImage 设置的 UITabBarItem 背景在 iPhone X 上未对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47055029/