我如何在标签栏项目上添加自定义视图

How i can add custom view on tab bar item

我需要在标签栏项目上添加两条垂直线。我该怎么做?谢谢

添加下一个代码:

var imageLeft: UIImageView?
var imageRight: UIImageView?

override func viewDidLoad() {
    super.viewDidLoad()

    let grayColor = UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 1.0)
    let leftLine = (tabBar.frame.width/2) - ((tabBar.frame.width/5)/2)
    let rightLine = (tabBar.frame.width/2) + ((tabBar.frame.width/5)/2)
    imageLeft = UIImageView(image: createImage(color: grayColor, size: tabBar.frame.size, x: leftLine))
    imageRight = UIImageView(image: createImage(color: grayColor, size: tabBar.frame.size, x: rightLine))
    tabBar.addSubview(imageLeft!)
    tabBar.addSubview(imageRight!)
}

func createImage(color: UIColor, size: CGSize, x: CGFloat) -> UIImage {
    let rect: CGRect = CGRect(x: x, y: 5, width: 1, height: tabBar.frame.height - 11)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

我的结果:

您需要使用自定义标签栏。 这是一个关于如何制作的教程:https://github.com/codepath/ios_guides/wiki/Creating-a-Custom-Tab-Bar

或者您可以在 Github

上找到可以为您完成此操作的图书馆

为此,您可以子类化 UITabBarController 并在您希望的位置添加一个 UIImageView:

class TabBarController: UITabBarController {

    var image: UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()
        image = UIImageView(image: createImage(color: UIColor(red:0.18, green:0.66, blue:0.24, alpha:1.0), size: tabBarItemSize, lineHeight: 4))
        tabBar.addSubview(image!)
    }

    func createImage(color: UIColor, size: CGSize, lineHeight: CGFloat) -> UIImage {
        let rect: CGRect = CGRect(x: 0, y: size.height - lineHeight, width: size.width, height: lineHeight )
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

您需要根据需要修改此设置并计算您希望它所在的位置,但这应该会有所帮助。我在 an article I wrote.

中进一步阐述了这一点