swift自訂tabBar

來源:互聯網
上載者:User

標籤:

class TabBarViewController: UITabBarController
{
    var tabBarBgImg : UIImageView?
    var tabBarBgImgSelected : UIImageView?
    var selectedButton : UIButton? // 標記選中的按鈕
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.lightGrayColor()
        

// 移除系統tabBar,添加自訂tabBar
        self.tabBar.removeFromSuperview()
        var customTabBar = UIView(frame: self.tabBar.frame)
        customTabBar.backgroundColor = UIColor.clearColor()
        self.view.addSubview(customTabBar)
        

// 添加兩個控制器到tabBar
        self.viewControllers = [UINavigationController(rootViewController: HomeViewController()), UINavigationController(rootViewController: GameViewController())]
        

// 添加按鈕到自訂的tabBar
        var btnsCount : Int = 2
        for temp in 0...1
        {
            var btnH : CGFloat = 60
            var btnW : CGFloat = UIScreen.mainScreen().bounds.size.width / CGFloat(btnsCount)
            var btnX : CGFloat = CGFloat(temp) * btnW
            var btnY : CGFloat = 0
            var btn = PPTabBarButton(frame: CGRectMake(btnX, btnY, btnW, btnH))
            customTabBar.addSubview(btn)
            btn.tag = temp
            btn.addTarget(self, action: "didClickButton:", forControlEvents: UIControlEvents.TouchUpInside)
            btn.setBackgroundImage(UIImage(named: "frame-new&hot-top-normal"), forState: UIControlState.Normal)
            btn.setBackgroundImage(UIImage(named: "frame-new&hot-top-pressed"), forState: UIControlState.Selected)
            
            if temp == 0
            {
                btn.selected = true
                self.selectedButton = btn
            }

// 設定按鈕背景圖片
            if temp == 0
            {
                btn.setImage(UIImage(named: "tab-video-line"), forState: UIControlState.Normal)
                btn.setImage(UIImage(named: "tab-video-solid"), forState: UIControlState.Selected)
            }
            else if temp == 1
            {
                btn.setImage(UIImage(named: "tab-game-line"), forState: UIControlState.Normal)
                btn.setImage(UIImage(named: "tab-game-solid"), forState: UIControlState.Selected)
            }
        }
    }
    
    func didClickButton (button : UIButton) -> Void
    {
        self.selectedButton?.selected = false
        button.selected = true
        self.selectedButton = button
        self.selectedIndex = button.tag
    }

}

  

swift自訂tabBar

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.