是否可以自定义UITabBarItem徽章? [英] Is it possible to customize UITabBarItem Badge?
问题描述
以下问题与我的类似.
如何将自定义UIImage用作UITabBarItem徽章?
是否可以使用背景图像代替自己绘制背景图像? 我认为这很好,因为我的应用程序将仅使用一个1位数的badgeValue.
Is it possible to use a background image instead of drawing it myself? I think it's fine since my app will only use a 1-digit badgeValue.
如果不可能,我想知道是否可以更改徽章颜色. 以下问题的答案并没有真正的帮助.
If it is not really possible, I want to know if we can change the badge color instead. The answers in the question below are not really helping.
推荐答案
这是您最好的选择.在文件范围内添加此扩展名,您可以根据需要自定义徽标.只需在您的任何根视图控制器中调用self.tabBarController!.setBadges([1,0,2])
.
This is your best bet. Add this extension at the file scope and you can customise the badges however you like. Just call self.tabBarController!.setBadges([1,0,2])
in any of your root view controllers.
请注意,这是一个包含三个项目的标签栏,其徽章值从左到右.
To be clear that is for a tab bar with three items, with the badge values going from left to right.
如果要添加图像,只需更改addBadge
方法
If you want to add images instead just change the addBadge
method
extension UITabBarController {
func setBadges(badgeValues: [Int]) {
var labelExistsForIndex = [Bool]()
for _ in badgeValues {
labelExistsForIndex.append(false)
}
for view in self.tabBar.subviews where view is PGTabBadge {
let badgeView = view as! PGTabBadge
let index = badgeView.tag
if badgeValues[index] == 0 {
badgeView.removeFromSuperview()
}
labelExistsForIndex[index] = true
badgeView.text = String(badgeValues[index])
}
for i in 0...(labelExistsForIndex.count - 1) where !labelExistsForIndex[i] && (badgeValues[i] > 0) {
addBadge(index: i, value: badgeValues[i], color: .red, font: UIFont(name: "Helvetica-Light", size: 11)!)
}
}
func addBadge(index: Int, value: Int, color: UIColor, font: UIFont) {
let itemPosition = CGFloat(index + 1)
let itemWidth: CGFloat = tabBar.frame.width / CGFloat(tabBar.items!.count)
let bgColor = color
let xOffset: CGFloat = 5
let yOffset: CGFloat = -12
let badgeView = PGTabBadge()
badgeView.frame.size = CGSize(width: 12, height: 12)
badgeView.center = CGPoint(x: (itemWidth * itemPosition) - (itemWidth / 2) + xOffset, y: 20 + yOffset)
badgeView.layer.cornerRadius = badgeView.bounds.width/2
badgeView.clipsToBounds = true
badgeView.textColor = UIColor.white
badgeView.textAlignment = .center
badgeView.font = font
badgeView.text = String(value)
badgeView.backgroundColor = bgColor
badgeView.tag = index
tabBar.addSubview(badgeView)
}
}
class PGTabBadge: UILabel { }
这篇关于是否可以自定义UITabBarItem徽章?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!