如何以编程方式创建具有自定义标签栏形状的自定义标签栏控制器

时间:2019-03-09 00:54:51

标签: ios swift uitabbarcontroller uitabbar

我正在尝试完全使用代码创建iOS移动应用。这样做会导致我的自定义标签栏控制器具有自定义标签栏形状的问题。

My custom tab bar shape looks something along the lines of this

AppDelegate.swift:

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow()
    window.rootViewController = CustomTabBarController()
    window?.makeKeyAndVisible()
    return true
}

在我的自定义TabBarController中:

import UIKit

class CustomTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupCenterButton()
    }

    func setupCenterButton() {
        let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))

        var menuButtonFrame = menuButton.frame
        menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height - 48
        menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
        menuButton.frame = menuButtonFrame
        menuButton.clipsToBounds = true
        menuButton.layer.cornerRadius = menuButtonFrame.height/2
        view.addSubview(menuButton)
    }


}


extension UITabBar {

    open override func sizeThatFits(_ size: CGSize) -> CGSize {
        return CGSize(width: size.width, height: 64)
    }
}

还有我的自定义标签栏形状

import UIKit

class CustomizedTabBar: UITabBar {

private var shapeLayer: CALayer?

private func addShape() {
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = createPath()

    if let oldShapeLayer = self.shapeLayer {
        self.layer.replaceSublayer(oldShapeLayer, with: shapeLayer)
    } else {
        self.layer.insertSublayer(shapeLayer, at: 0)
    }

    self.shapeLayer = shapeLayer
}

func createPath() -> CGPath {
    let path = UIBezierPath()

    path.move(to: CGPoint(x: 0, y: 0))
    //..path moving around..
    path.close()

    return path.cgPath
}

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    //..stuff
}

override func draw(_ rect: CGRect) {
    self.addShape()
}

func createBezierPath() -> UIBezierPath {

    //..creating a path
}

我该如何解决?在当前代码设置下,我的标签栏像普通的标签栏一样出现...而不是我的自定义形状 see here

,并且我尝试在UITabBarController中覆盖我的选项卡栏属性以返回CustomizedBarBar类的实例,但是没有运气。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

请尝试以这种方式运行,并让我知道。

class MyTab: UITabBar {

}
class MyTabBarController: UITabBarController {
    override var tabBar: UITabBar {
        return MyTab()
    }
}

答案 1 :(得分:0)

如果您使用故事板,那么使用自定义标签栏是微不足道的。

  1. 创建您的自定义 UITabBar 子类。
  2. 将标签栏控制器拖到故事板上。
  3. 在故事板中选择标签栏对象,点击“身份检查器”,然后将标签栏的类更改为您自定义的标签栏类。