向UITabBarController添加自定义按钮(在中心添加按钮)

时间:2017-04-06 05:23:14

标签: swift uibutton uitabbarcontroller

我试图使用我制作的一些图片制作自定义标签栏,但我遇到了一些麻烦。我试图在标签栏上添加一个按钮,看起来我无法做到。我想做这样的事情:http://a4.mzstatic.com/us/r30/Purple122/v4/6a/43/85/6a438540-94f5-a549-f0b4-3b94d63fbc95/screen696x696.jpeg

然后为该按钮添加一些动画。我该如何添加该按钮?我需要继承UITabBarController吗?谢谢!

2 个答案:

答案 0 :(得分:1)

在TabbarController类中,添加此代码

override func viewDidLoad() {
    super.viewDidLoad()
    setupMiddleButton()

}




// MARK: - AddButton

func setupCenterButton() {
    let centerButton = UIButton(frame: CGRect(x: 0, y: 10, width: 45, height: 45))

    var centerButtonFrame = centerButton.frame
    centerButtonFrame.origin.y = (view.bounds.height - centerButtonFrame.height) - 2
    centerButtonFrame.origin.x = view.bounds.width/2 - centerButtonFrame.size.width/2
    centerButton.frame = centerButtonFrame

    centerButton.layer.cornerRadius = 35
    view.addSubview(centerButton)

    centerButton.setBackgroundImage(#imageLiteral(resourceName: "tabPost"), for: .normal)
    centerButton.addTarget(self, action: #selector(centerButtonAction(sender:)), for: .touchUpInside)

    view.layoutIfNeeded()
}

// MARK: - Center button Actions

@objc private func centerButtonAction(sender: UIButton) {
    selectedIndex = 2
}

它会工作.. :))

答案 1 :(得分:-1)

您应该实现UITabBarControllerDelegate的委托方法:

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {


    if viewController == (self.tabBarController?.viewControllers?[theIndexOfTheButton])! {

      // do my stuffs here  
      return false

    }
    return true
}

不要忘记设置self.tabBarController?.delegate = self