UITabBar个性化,颜色和分隔线

时间:2017-07-18 01:29:55

标签: ios swift uitabbar

我正在制作这个有应用程序栏的iOS应用程序(Swift 3),我找不到按照我想要的方式对其进行个性化的方法。我想在每个图标之间添加线条,我希望它在选中时为红色,如下所示:

UITabBar

1 个答案:

答案 0 :(得分:1)

自定义从UITabBarController继承的类,然后将其用作TabBarController的类。这里提供的主要程序是:

import UIKit

class MainTabBarController: UITabBarController,UITabBarControllerDelegate {

    var firstBackgroundView:UIView!
    //var secondBackgroundView:UIView!        
    //......

    override func viewDidLoad() {
        super.viewDidLoad()

        //Lines:
        let topline = CALayer()
        topline.frame = CGRect(x: 0, y: 0, width: self.tabBar.frame.width, height: 2)
        topline.backgroundColor = UIColor.gray.cgColor
        self.tabBar.layer.addSublayer(topline)

        let firstVerticalLine = CALayer()
        firstVerticalLine.frame = CGRect(x: self.tabBar.frame.width / 5, y: 0, width: 2, height: self.tabBar.frame.height)
        firstVerticalLine.backgroundColor = UIColor.gray.cgColor
        self.tabBar.layer.addSublayer(firstVerticalLine)

        //Continue to add other lines to divide tab items...
        //......

        //Background views
        firstBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.tabBar.frame.width / 5, height: self.tabBar.frame.height))
        firstBackgroundView.backgroundColor = UIColor.red
        firstBackgroundView.isHidden = false //true for others.
        self.tabBar.addSubview(firstBackgroundView)
        self.tabBar.sendSubview(toBack: firstBackgroundView)

        //Continue to add other background views for each tab item...
        //......


        self.delegate = self
    }

    public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if self.selectedIndex == 0 {
            firstBackgroundView.isHidden = false
            //othersBackgroundView.isHidden = true
        }
        else if self.selectedIndex == 1 {
            //......
        }
    }
}