我在标签栏上显示徽章,但是当数字增加时,它会显示在标签栏项目中,如图所示
我想稍微向左移动徽章视图,使其适合选定的选项卡image.i尝试here描述,但没有运气。那么有没有办法调整徽章视图位置?任何帮助将不胜感激。
我发现Kateryna的答案对于让我走上正轨非常有用,但我不得不稍微更新一下:
func repositionBadge(tab: Int){
for badgeView in self.tabBarController!.tabBar.subviews[tab].subviews {
if NSStringFromClass(badgeView.classForCoder) == "_UIBadgeView" {
badgeView.layer.transform = CATransform3DIdentity
badgeView.layer.transform = CATransform3DMakeTranslation(-17.0, 1.0, 1.0)
}
}
}
请注意,选项卡整数不是零索引,因此第一个选项卡将是数字1,第二个选项卡将是2,等等。
更新徽章值时,请添加以下方法:
func updateBadge(#value: UInt, tabBarItemTag: Int) {
self.viewControllerForTag(tabBarItemTag)?.tabBarItem.badgeValue = value
for badgeView in (tabBar.subviews[tabBarItemTag] as! UIView).subviews {
let className = "\(_stdlib_getDemangledTypeName(badgeView))"
if className.rangeOfString("BadgeView").location != NSNotFound {
badgeView.layer.transform = CATransform3DIdentity
badgeView.layer.transform = CATransform3DMakeTranslation(0.0, 10.0, 20.0)
}
}
}
您需要使用第二个CATransform3DMakeTranslation来进行正确定位。在此代码中,徽章在底部/左侧移动一点。首先需要CATransform3DMakeTranslation来假装徽章移动。它是一个Swift代码,但您可以轻松地将其转换为Objective-C。
默认情况下,徽章与标签栏图像对齐。如果您将大图像添加为标签栏项目图像,则可以使用以下代码进行调整。
for tabBarButton in self.tabBar.subviews{
for badgeView in tabBarButton.subviews{
var className=NSStringFromClass(badgeView.classForCoder)
if className == "_UIBadgeView"
{
badgeView.layer.transform = CATransform3DIdentity
badgeView.layer.transform = CATransform3DMakeTranslation(-17.0, 1.0, 1.0)
}
}
}
在Objective-C中:
for (UIView *tabBarButton in self.navigationController.tabBarController.tabBar.subviews)
{
for (UIView *badgeView in tabBarButton.subviews)
{
NSString *className = NSStringFromClass([badgeView class]);
// Looking for _UIBadgeView
if ([className rangeOfString:@"BadgeView"].location != NSNotFound)
{
badgeView.layer.transform = CATransform3DIdentity;
badgeView.layer.transform = CATransform3DMakeTranslation(-5.0, 1.0, 1.0);
}
}
}
在C#Xamarin中
void RepositionBadge(int tab)
{
foreach (var badgeView in TabBar.Subviews[tab].Subviews)
{
if (badgeView.Class.Name == "_UIBadgeView")
{
badgeView.Layer.Transform = CATransform3D.Identity;
badgeView.Layer.Transform = CATransform3D.MakeTranslation(-10.0f, 1.0f, 1.0f);
}
}
}
我为UITabBar
创建了一个扩展程序,它可以获得徽章视图和徽章的标签:
extension UITabBar {
func badgeViewForItem(at index: Int) -> UIView? {
guard subviews.count > index else {
return nil
}
return subviews[index].subviews.first(where: { NSStringFromClass($0.classForCoder) == "_UIBadgeView" })
}
func labelForItem(at index: Int) -> UILabel? {
guard subviews.count > index else {
return nil
}
return badgeViewForItem(at: index)?.subviews.first(where: { $0 is UILabel }) as? UILabel
}
}
然后你可以这样做:
let firstItemBadgeView = badgeViewForItem(at: 0)!
// Do something with the badge view like setting the border, background color ...
// ex: firstItemBadgeView.backgroundColor = UIColor.clear