ios 是否可以更改 UITabBarItem 徽章颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13341603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to change UITabBarItem badge color
提问by 1110
I want to change background color of UITabBarItem
badgebut can't find any resource on how to make it.
我想更改UITabBarItem
徽章的背景颜色,但找不到有关如何制作的任何资源。
回答by Nuno Gon?alves
UITabBarItem
has this available since iOS 10.
UITabBarItem
自 iOS 10 起有此功能。
var badgeColor: UIColor? { get set }
It's also available via appearence.
它也可以通过外观获得。
if #available(iOS 10, *) {
UITabBarItem.appearance().badgeColor = .green
}
reference docs: https://developer.apple.com/reference/uikit/uitabbaritem/1648567-badgecolor
参考文档:https: //developer.apple.com/reference/uikit/uitabbaritem/1648567-badgecolor
回答by Hans Kn?chel
Changing the badge-color is now natively supported in iOS 10 and later using the badgeColor
property inside your UITabBarItem
. See the apple docsfor more infos on the property.
改变徽章的颜色现在原生支持iOS中10和以后使用badgeColor
您的内部属性UITabBarItem
。有关该属性的更多信息,请参阅Apple 文档。
Example:
例子:
- Swift 3:
myTab.badgeColor = UIColor.blue
- Objective-C:
[myTab setBadgeColor:[UIColor blueColor]];
- 斯威夫特 3:
myTab.badgeColor = UIColor.blue
- 目标-C:
[myTab setBadgeColor:[UIColor blueColor]];
回答by cnotethegr8
I wrote this piece of code for my app, but I have only tested it in iOS 7.
我为我的应用程序编写了这段代码,但我只在 iOS 7 中对其进行了测试。
for (UIView* tabBarButton in self.tabBar.subviews) {
for (UIView* badgeView in tabBarButton.subviews) {
NSString* className = NSStringFromClass([badgeView class]);
// looking for _UIBadgeView
if ([className rangeOfString:@"BadgeView"].location != NSNotFound) {
for (UIView* badgeSubview in badgeView.subviews) {
NSString* className = NSStringFromClass([badgeSubview class]);
// looking for _UIBadgeBackground
if ([className rangeOfString:@"BadgeBackground"].location != NSNotFound) {
@try {
[badgeSubview setValue:[UIImage imageNamed:@"YourCustomImage.png"] forKey:@"image"];
}
@catch (NSException *exception) {}
}
if ([badgeSubview isKindOfClass:[UILabel class]]) {
((UILabel *)badgeSubview).textColor = [UIColor greenColor];
}
}
}
}
}
You're only able to update the badge background with an image, not a color. I have also exposed the badge label if you wanted to update that in some way.
您只能使用图像而不是颜色来更新徽章背景。如果您想以某种方式更新它,我还公开了徽章标签。
Its important to note that this code must be called after setting the tabBarItem.badgeValue
!
需要注意的是,必须在设置tabBarItem.badgeValue
!
EDIT: 4/14/14
编辑:4/14/14
The above code will work in iOS 7 when called anywhere. To get it working in iOS 7.1 call it in the view controllers -viewWillLayoutSubviews
.
当在任何地方调用时,上面的代码将在 iOS 7 中工作。要使其在 iOS 7.1 中工作,请在视图控制器中调用它-viewWillLayoutSubviews
。
EDIT: 12/22/14
编辑:12/22/14
Here's an updated snippet which I'm currently using. I put the code in a category extension for simplicity.
这是我目前正在使用的更新片段。为简单起见,我将代码放在类别扩展中。
- (void)badgeViews:(void (^)(UIView* badgeView, UILabel* badgeLabel, UIView* badgeBackground))block {
if (block) {
for (UIView* tabBarButton in self.subviews) {
for (UIView* badgeView in tabBarButton.subviews) {
NSString* className = NSStringFromClass([badgeView class]);
if ([className rangeOfString:@"BadgeView"].location != NSNotFound) {
UILabel* badgeLabel;
UIView* badgeBackground;
for (UIView* badgeSubview in badgeView.subviews) {
NSString* className = NSStringFromClass([badgeSubview class]);
if ([badgeSubview isKindOfClass:[UILabel class]]) {
badgeLabel = (UILabel *)badgeSubview;
} else if ([className rangeOfString:@"BadgeBackground"].location != NSNotFound) {
badgeBackground = badgeSubview;
}
}
block(badgeView, badgeLabel, badgeBackground);
}
}
}
}
}
Then when you're ready to call it, it'll look like this.
然后当你准备好调用它时,它看起来像这样。
[self.tabBar badgeViews:^(UIView *badgeView, UILabel *badgeLabel, UIView *badgeBackground) {
}];
EDIT: 11/16/15
编辑:11/16/15
It's been brought to my attention that some people need a little more clarity on what's happening in this code. The for loops are searching for a few views which are not publicly accessible. By checking if the views class name contains a part of the expected name, it's ensuring to reach the intended view while not setting off any possible red flags by Apple. Once everything has been located, a block is executed with easy access to these views.
我注意到有些人需要更清楚地了解这段代码中发生的事情。for 循环正在搜索一些不可公开访问的视图。通过检查视图类名称是否包含预期名称的一部分,可以确保到达预期视图,同时不会引发 Apple 任何可能的危险信号。一旦找到所有内容,就可以轻松访问这些视图来执行块。
It's noteworthy that the possibility exists for this code to stop working in a future iOS update. For example these internal views could one day acquire different class names. However the chances of that are next to none since even internally Apple rarely refactors classes to this nature. But even if they were to, it would be something along the title of UITabBarBadgeView
, which would still reach the expected point in code. Being that iOS9 is well out the door and this code is still working as intended, you can expect this problem to never arise.
值得注意的是,此代码有可能在未来的 iOS 更新中停止工作。例如,这些内部视图有一天可能会获得不同的类名。然而,这种可能性几乎为零,因为即使在 Apple 内部,也很少将类重构为这种性质。但即使他们这样做了,它也会是 标题中的东西UITabBarBadgeView
,它仍然会达到代码中的预期点。由于 iOS9 已经过时并且这段代码仍然按预期工作,因此您可以预期这个问题永远不会出现。
回答by eold
I have the same problem and solved it by creating a little category that replace the BadgeView with an UILabel that you can customize easily.
我遇到了同样的问题,并通过创建一个小类别来解决它,该类别将 BadgeView 替换为可以轻松自定义的 UILabel。
回答by Kirualex
For people using Swift, I managed to improve on TimWhiting answer in order to have the badge view working on any screen size and any orientation.
对于使用 Swift 的人,我设法改进了 TimWhiting 的答案,以便让徽章视图可以在任何屏幕尺寸和任何方向上工作。
extension UITabBarController {
func setBadges(badgeValues: [Int]) {
for view in self.tabBar.subviews {
if view is CustomTabBadge {
view.removeFromSuperview()
}
}
for index in 0...badgeValues.count-1 {
if badgeValues[index] != 0 {
addBadge(index, value: badgeValues[index], color:UIColor(paletteItem: .Accent), font: UIFont(name: Constants.ThemeApp.regularFontName, size: 11)!)
}
}
}
func addBadge(index: Int, value: Int, color: UIColor, font: UIFont) {
let badgeView = CustomTabBadge()
badgeView.clipsToBounds = true
badgeView.textColor = UIColor.whiteColor()
badgeView.textAlignment = .Center
badgeView.font = font
badgeView.text = String(value)
badgeView.backgroundColor = color
badgeView.tag = index
tabBar.addSubview(badgeView)
self.positionBadges()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.positionBadges()
}
// Positioning
func positionBadges() {
var tabbarButtons = self.tabBar.subviews.filter { (view: UIView) -> Bool in
return view.userInteractionEnabled // only UITabBarButton are userInteractionEnabled
}
tabbarButtons = tabbarButtons.sort({ extension UITabBarController {
func setBadges(badgeValues: [Int]) {
for view in self.tabBar.subviews {
if view is CustomTabBadge {
view.removeFromSuperview()
}
}
for index in 0...badgeValues.count-1 {
if badgeValues[index] != 0 {
addBadge(index: index, value: badgeValues[index], color: UIColor.blue, font: UIFont(name: "Helvetica-Light", size: 11)!)
}
}
}
func addBadge(index: Int, value: Int, color: UIColor, font: UIFont) {
let badgeView = CustomTabBadge()
badgeView.clipsToBounds = true
badgeView.textColor = UIColor.white
badgeView.textAlignment = .center
badgeView.font = font
badgeView.text = String(value)
badgeView.backgroundColor = color
badgeView.tag = index
tabBar.addSubview(badgeView)
self.positionBadges()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.positionBadges()
}
// Positioning
func positionBadges() {
var tabbarButtons = self.tabBar.subviews.filter { (view: UIView) -> Bool in
return view.isUserInteractionEnabled // only UITabBarButton are userInteractionEnabled
}
tabbarButtons = tabbarButtons.sorted(by: { extension UITabBarController {
func setBadges(badgeValues:[Int]){
var labelExistsForIndex = [Bool]()
for value in badgeValues {
labelExistsForIndex.append(false)
}
for view in self.tabBar.subviews {
if view.isKindOfClass(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 var i=0;i<labelExistsForIndex.count;i++ {
if labelExistsForIndex[i] == false {
if badgeValues[i] > 0 {
addBadge(i, value: badgeValues[i], color:UIColor(red: 4/255, green: 110/255, blue: 188/255, alpha: 1), 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 = 12
let yOffset:CGFloat = -9
var badgeView = PGTabBadge()
badgeView.frame.size=CGSizeMake(17, 17)
badgeView.center=CGPointMake((itemWidth * itemPosition)-(itemWidth/2)+xOffset, 20+yOffset)
badgeView.layer.cornerRadius=badgeView.bounds.width/2
badgeView.clipsToBounds=true
badgeView.textColor=UIColor.whiteColor()
badgeView.textAlignment = .Center
badgeView.font = font
badgeView.text = String(value)
badgeView.backgroundColor = bgColor
badgeView.tag=index
tabBar.addSubview(badgeView)
}
}
class PGTabBadge: UILabel {
}
.frame.origin.x < .frame.origin.x })
for view in self.tabBar.subviews {
if view is CustomTabBadge {
let badgeView = view as! CustomTabBadge
self.positionBadge(badgeView: badgeView, items:tabbarButtons, index: badgeView.tag)
}
}
}
func positionBadge(badgeView: UIView, items: [UIView], index: Int) {
let itemView = items[index]
let center = itemView.center
let xOffset: CGFloat = 12
let yOffset: CGFloat = -14
badgeView.frame.size = CGSize(width: 17, height: 17)
badgeView.center = CGPoint(x: center.x + xOffset, y: center.y + yOffset)
badgeView.layer.cornerRadius = badgeView.bounds.width/2
tabBar.bringSubview(toFront: badgeView)
}
}
class CustomTabBadge: UILabel {}
.frame.origin.x < .frame.origin.x })
for view in self.tabBar.subviews {
if view is CustomTabBadge {
let badgeView = view as! CustomTabBadge
self.positionBadge(badgeView, items:tabbarButtons, index: badgeView.tag)
}
}
}
func positionBadge(badgeView: UIView, items: [UIView], index: Int) {
let itemView = items[index]
let center = itemView.center
let xOffset: CGFloat = 12
let yOffset: CGFloat = -14
badgeView.frame.size = CGSizeMake(17, 17)
badgeView.center = CGPointMake(center.x + xOffset, center.y + yOffset)
badgeView.layer.cornerRadius = badgeView.bounds.width/2
tabBar.bringSubviewToFront(badgeView)
}
}
class CustomTabBadge: UILabel {}
回答by thecloud_of_unknowing
Swift 3Here is an updated version of @Kirualex's answer (who improved on @TimWhiting's answer) for Swift 3.
Swift 3这是Swift 3的@Kirualex 答案的更新版本(改进了@TimWhiting 的答案)。
if #available(iOS 10.0, *)
{
self.kAppTabBarController.tabBar.items![1].badgeColor = YOUR_COLOR
}
回答by TimWhiting
No you can't change the color but you can use your own badges instead. 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.
不,您不能更改颜色,但您可以使用自己的徽章。在文件范围内添加此扩展名,您可以根据自己的喜好自定义徽章。只需调用self.tabBarController!.setBadges([1,0,2])
任何根视图控制器即可。
To be clear that is for a tab bar with three items, with the badge values going from left to right.
需要明确的是,这是一个包含三个项目的标签栏,徽章值从左到右。
##代码##回答by RomanN
It appears that no. You may only set the value. From Apple's documentation badge is:
看来没有。您只能设置该值。来自 Apple 的文档徽章是:
Text that is displayed in the upper-right corner of the item with a surrounding redoval.
显示在项目右上角的文本,周围带有红色椭圆。
回答by Parimal
You need to specify tab item at index to change badge color, #available in iOS 10 ,
您需要在索引处指定标签项以更改徽章颜色,#available in iOS 10 ,
##代码##