如何在Swift中为选定的UITabBarItem图标下方添加小图标

4

我有一个继承自UITabBarController的子类,我想在选中的UITabBarItem图标下方添加一个小的白色矩形图标。我使用了一个UIView,并将TabBarItem作为其子视图,并将该视图作为其子视图添加到其中。我在viewWillAppear方法中这样做,它显示出来了,但当我选择另一个选项卡时,它不会出现在那个选项卡下面。

以下是我的代码:

let view =  orderedTabBarItemViews()[selectedIndex]

bottomIcon.frame = CGRect(x: 0, y: 42, width: 10, height: 3)
bottomIcon.center = CGPoint(x: view.bounds.size.width / 2, y: view.bounds.size.height / 2)
bottomIcon.backgroundColor = UIColor.white
bottomIcon.layer.cornerRadius = 2

view.addSubview(bottomIcon)
orderedTabBarItemViews()函数将TabBarItem作为UIView数组返回。下面是我想要实现的效果的图片。
3个回答

2

我使用Unicode字符⬬创建了一个快速的技巧:

extension UITabBarController {

    func addDotToTabBarItemWith(index: Int,size: CGFloat,color: UIColor, verticalOffset: CGFloat = 1.0) {

        // set distance from tab bar icons
         for tabItem in self.viewControllers! {
            tabItem.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0.0, vertical: verticalOffset)
        }

        // set default appearance for tabbar icon title
        UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: color,NSFontAttributeName:UIFont(name: "American Typewriter", size: size)!], for: .normal)
        UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: color,NSFontAttributeName:UIFont(name: "American Typewriter", size: size)!], for: .selected)

        // place the dot
        guard let vc = self.viewControllers?[index] else {
            log.error("Couldn't find a TabBar Controller with index:\(index)")
            return
        }

        vc.tabBarItem.title = "⬬"
    }
}

1
我认为没有一种方便的方法来添加和显示/隐藏视图。
我建议您使用UIImage来完成这个任务 - 所以一个带有点的用于选中状态,另一个不带点的用于非选中状态。

1

有几个选项:

  1. 将其作为所选图像的一部分添加。这是最简单的解决方案。

  2. 使用大号字体将其作为标签页添加(例如使用 - 字符或一些更好的Unicode字符,例如 )。

  3. 将其作为覆盖层添加到 UITabBar


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接