ios - UITabBar.appearance().selectionIndicatorImage 设置的 UITabBarItem 背景在 iPhone X 上未对齐

标签 ios swift iphone-x

代码:

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

在普通设备上看起来像这样:

enter image description here

在 iPhone X 上是这样的:

enter image description here

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)
  }

enter image description here


更新 2:

上面的代码从 viewDidLoad 调用(也尝试从 viewWillAppear)。 UITabBarController 的子类 100% 由代码编写(未使用 Storyboard/Xib)。


更新 3:

我们还有一个自定义按钮作为 subview 添加到 UITabBar 并正确定位。只有 selectionIndicatorImage 未对齐...

enter image description here


更新 4:

viewDidAppear 而不是 viewDidLoadviewWillAppear 中运行上面的原始代码会产生以下结果:

enter image description here

最佳答案

你只需要在延迟之后调用它,因为在你的情况下它没有得到正确的 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/

相关文章:

ios - 核心数据不会在两次发布之间持续存在

ios - 在常量初始化中使用 IBoutlet

ios - 当前 View : Swift 3

iphone-x - 如何在iPhone上设置状态栏颜色?

ios - 在 iPhone X 模拟器的顶部和底部看到黑条

ios - 如何让 UITabBar 在 iPhone X 上延伸到底部?

ios - SwiftUI 在 NavigationLink View 中隐藏 TabView 栏

ios - 跟踪节点行中的第一个节点

ios - uiimage 模拟器图像无法缩放

ios - 有关 Swift 中等待批准的计划通知的问题