如何在UITabBar徽章上添加边框?

时间:2018-11-29 10:58:31

标签: ios uitabbarcontroller uitabbaritem

如何在标签栏项的徽章中添加自定义边框?默认情况下,它在选项卡栏项目的右上角显示一个红点。我想为其添加边框。可以更改徽章的颜色,但是找不到任何可以为徽章添加边框的东西。

1 个答案:

答案 0 :(得分:1)

我认为没有正式的方法可以在徽章上添加边框,但是我也想这样做,最终我开发了自己的方法。我的解决方案更像是一种骇客,但它可以在Xcode 10.1和iOS 12.1上运行,并且不会拒绝您的应用程序,因此对您来说足够好了。

最困难的部分是实际获得徽章,这是具有5个标签的标签栏的视图层次结构:

enter image description here

您可以看到,在我的项目中,最后一个标签包含徽章。但是实际上是带有徽章的第4个标签(带有index = 3的标签),这是因为我将第4个标签放在UITabBarController类的顶部,因此不会裁剪徽章,以防显示更大的值。这是我获取徽章视图的方式(这是在UITabBar上下文中,因此self是UITabBar):

func badge(forIndex index: Int) -> UIView? {
    let sorted = self.subviews.sorted { (view1, view2) -> Bool in // I need to sort it by the frame.origin.x because the order in the subviews array cannot be trusted, I got random order there during my tests
        return view1.frame.origin.x < view2.frame.origin.x
    }
    let idx = index + 1 // the first view is actually a _UIBarBackground
    guard let barItemView = sorted[safe: idx] else {
        print("\(#file):\(#function):\(#line): Could not find a subview with index \(idx) in \(self)")
        return nil
    }
    if barItemView.subviews.count == 3 { // this is a hack, but I could not find a better way to get the badge without using private interfaces
        let view = barItemView.subviews.last
        return view
    }
    return nil
}

这为您提供了徽章视图,并且在最困难(最丑陋)的部分后面,我们现在可以添加边框(或像在项目中一样更改位置):

if let badgeView = badge(forIndex: index) {
    // I found that it's easier to transform the layer here instead of the view, because it's instantaneous
    let badgeViewLayer = badgeView.layer
    badgeViewLayer.transform = CATransform3DMakeTranslation(BadgeTranslationX, BadgeTranslationY, 1) // you can change the position of the badge with this

    guard let badgeViewImageView = badgeView.subviews.first else {
        print("\(#file):\(#function):\(#line): No image view inside the badge view")
        return
    }

    badgeViewImageView.clipsToBounds = true // this is important, otherwise you may get artifacts when working with rounded corners etc.
    let layer = badgeViewImageView.layer
    layer.borderColor = UIColor.white.cgColor
    layer.borderWidth = 2
    layer.cornerRadius = 8
}

这是上面的代码所提供的:

enter image description here

当然,颜色可以是任何东西:

enter image description here