web-dev-qa-db-ja.com

タブバーのカスタムボタンを丸くする

これが私がやろうとしていることです: enter image description here

注:スクリーンショットは以前のバージョンのiOSから取られています

私が達成できたこと: enter image description here

コード:

 override func viewWillAppear(animated: Bool) {
    // Creates image of the Button
    let imageCameraButton: UIImage! = UIImage(named: "cameraIcon")

    // Creates a Button
    let cameraButton = UIButton(type: .Custom)
    // Sets width and height to the Button
    cameraButton.frame = CGRectMake(0.0, 0.0, imageCameraButton.size.width, imageCameraButton.size.height);
    // Sets image to the Button
    cameraButton.setBackgroundImage(imageCameraButton, forState: .Normal)
    // Sets the center of the Button to the center of the TabBar
    cameraButton.center = self.tabBar.center
    // Sets an action to the Button
    cameraButton.addTarget(self, action: "doSomething", forControlEvents: .TouchUpInside)

    // Adds the Button to the view
    self.view.addSubview(cameraButton)
}

私は通常の方法で丸いボタンを作成しようとしましたが、これは結果でした:

enter image description here

丸いボタンのコードスニペット:

//Creation of Ronded Button
    cameraButton.layer.cornerRadius = cameraButton.frame.size.width/2
    cameraButton.clipsToBounds = true
20

溶液

UITabBarControllerをサブクラス化し、TabBarのビューの上にボタンを追加する必要があります。ボタンのアクションは、UITabBarControllerを設定してselectedIndexタブの変更をトリガーする必要があります。

コード

以下のコードは簡単なアプローチのみですが、フルサポートのiPhone(Xシリーズを含む)/ iPadバージョンについては、ここで完全なリポジトリを確認できます: EBRoundedTabBarController

class CustomTabBarController: UITabBarController {

    // MARK: - View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        let controller1 = UIViewController()
        controller1.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 1)
        let nav1 = UINavigationController(rootViewController: controller1)

        let controller2 = UIViewController()
        controller2.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 2)
        let nav2 = UINavigationController(rootViewController: controller2)

        let controller3 = UIViewController()
        let nav3 = UINavigationController(rootViewController: controller3)
        nav3.title = ""

        let controller4 = UIViewController()
        controller4.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 4)
        let nav4 = UINavigationController(rootViewController: controller4)

        let controller5 = UIViewController()
        controller5.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 5)
        let nav5 = UINavigationController(rootViewController: controller5)


        viewControllers = [nav1, nav2, nav3, nav4, nav5]
        setupMiddleButton()
    }

    // MARK: - Setups

    func setupMiddleButton() {
        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
        menuButtonFrame.Origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
        menuButton.frame = menuButtonFrame

        menuButton.backgroundColor = UIColor.red
        menuButton.layer.cornerRadius = menuButtonFrame.height/2
        view.addSubview(menuButton)

        menuButton.setImage(UIImage(named: "example"), for: .normal)
        menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)

        view.layoutIfNeeded()
    }


    // MARK: - Actions

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

出力

enter image description here

46
E-Riddie

Swift 3ソリューション

Swift 3)でこの作業を行うためにEricBのソリューションをわずかに調整すると、menuButton.addTarget()メソッドはセレクター構文を少し変更する必要があります。

新しいmenuButton.addTarget()関数は次のとおりです。

menuButton.addTarget(self, action: #selector(MyTabBarController.menuButtonAction), for: UIControlEvents.touchUpInside)

TabBarControllerクラスを定義するときに、UITabBarControllerDelegateも追加し、そのすべてを

override func viewDidAppear(_ animated: Bool) { ... }

明確にするために、完全なコードは次のとおりです。

完全なコードソリューション

import UIKit

class MyTabBarController: UITabBarController, UITabBarControllerDelegate {

// View Did Load
override func viewDidLoad() {
    super.viewDidLoad()

}

// Tab Bar Specific Code
override func viewDidAppear(_ animated: Bool) {
    let controller1 = UIViewController(self.view.backgroundColor = UIColor.white)
    controller1.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 1)
    let nav1 = UINavigationController(rootViewController: controller1)

    let controller2 = UIViewController()
    controller2.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 2)
    let nav2 = UINavigationController(rootViewController: controller2)

    let controller3 = UIViewController()
    let nav3 = UINavigationController(rootViewController: controller3)
    nav3.title = ""

    let controller4 = UIViewController()
    controller4.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 4)
    let nav4 = UINavigationController(rootViewController: controller4)

    let controller5 = UIViewController()
    controller5.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.contacts, tag: 5)
    let nav5 = UINavigationController(rootViewController: controller5)

    self.viewControllers = [nav1, nav2, nav3, nav4, nav5]
    self.setupMiddleButton()
}

// TabBarButton – Setup Middle Button
func setupMiddleButton() {
    let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
    var menuButtonFrame = menuButton.frame
    menuButtonFrame.Origin.y = self.view.bounds.height - menuButtonFrame.height
    menuButtonFrame.Origin.x = self.view.bounds.width / 2 - menuButtonFrame.size.width / 2
    menuButton.frame = menuButtonFrame

    menuButton.backgroundColor = UIColor.red
    menuButton.layer.cornerRadius = menuButtonFrame.height/2
    self.view.addSubview(menuButton)

    menuButton.setImage(UIImage(named: "example"), for: UIControlState.normal)
    menuButton.addTarget(self, action: #selector(MyTabBarController.menuButtonAction), for: UIControlEvents.touchUpInside)

    self.view.layoutIfNeeded()
}

// Menu Button Touch Action
func menuButtonAction(sender: UIButton) {
    self.selectedIndex = 2
    // console print to verify the button works
    print("Middle Button was just pressed!")
   }
 }
11
Brdjx

これは、UITabbarcontrollerのサブクラスであるcustomTabbarcontrollerクラスです。 @EridBによって与えられるのと同じ考えです。しかし、彼のコードでは@ Raymond26の問題は解決されませんでした。したがって、Swift 3.で記述された完全なソリューションを投稿します

protocol CustomTabBarControllerDelegate
{
    func customTabBarControllerDelegate_CenterButtonTapped(tabBarController:CustomTabBarController, button:UIButton, buttonState:Bool);
}

class CustomTabBarController: UITabBarController, UITabBarControllerDelegate
{
    var customTabBarControllerDelegate:CustomTabBarControllerDelegate?;
    var centerButton:UIButton!;
    private var centerButtonTappedOnce:Bool = false;

    override func viewDidLayoutSubviews()
    {
        super.viewDidLayoutSubviews();

        self.bringcenterButtonToFront();
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.delegate = self;

        self.tabBar.barTintColor = UIColor.red;

        let dashboardVC = DashboardViewController()        
        dashboardVC.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
        let nav1 = UINavigationController(rootViewController: dashboardVC)

        let myFriendsVC = MyFriendsViewController()
        myFriendsVC.tabBarItem = UITabBarItem(tabBarSystemItem: .featured, tag: 2)
        let nav2 = UINavigationController(rootViewController: myFriendsVC)

        let controller3 = UIViewController()
        let nav3 = UINavigationController(rootViewController: controller3)
        nav3.title = ""

        let locatorsVC = LocatorsViewController()
        locatorsVC.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag: 4)
        let nav4 = UINavigationController(rootViewController: locatorsVC)

        let getDirectionsVC = GetDirectionsViewController()
        getDirectionsVC.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 5)
        let nav5 = UINavigationController(rootViewController: getDirectionsVC)

        viewControllers = [nav1, nav2, nav3, nav4, nav5]

        self.setupMiddleButton()
    }

    // MARK: - TabbarDelegate Methods

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController)
    {
        switch viewController
        {
        case is DashboardViewController:
            self.showCenterButton()
        case is MyFriendsViewController:
            self.showCenterButton()
        case is GetDirectionsViewController:
            self.showCenterButton()
        case is LocatorsViewController:
            self.showCenterButton()
        default:
            self.showCenterButton()
        }
    }

    // MARK: - Internal Methods

    @objc private func centerButtonAction(sender: UIButton)
    {
        //        selectedIndex = 2
        if(!centerButtonTappedOnce)
        {
            centerButtonTappedOnce=true;
            centerButton.setImage(UIImage(named: "ic_bullseye_white"), for: .normal)
        }
        else
        {
            centerButtonTappedOnce=false;
            centerButton.setImage(UIImage(named: "ic_bullseye_red"), for: .normal)
        }

        customTabBarControllerDelegate?.customTabBarControllerDelegate_CenterButtonTapped(tabBarController: self,
                                                                                          button: centerButton,
                                                                                          buttonState: centerButtonTappedOnce);
    }

    func hideCenterButton()
    {
        centerButton.isHidden = true;
    }

    func showCenterButton()
    {
        centerButton.isHidden = false;
        self.bringcenterButtonToFront();
    }

    // MARK: - Private methods

    private func setupMiddleButton()
    {
        centerButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))

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

        centerButton.backgroundColor = UIColor.red
        centerButton.layer.cornerRadius = centerButtonFrame.height/2
        view.addSubview(centerButton)

        centerButton.setImage(UIImage(named: "ic_bullseye_red"), for: .normal)
        centerButton.setImage(UIImage(named: "ic_bullseye_white"), for: .highlighted)
        centerButton.addTarget(self, action: #selector(centerButtonAction(sender:)), for: .touchUpInside)

        view.layoutIfNeeded()
    }

    private func bringcenterButtonToFront()
    {
        print("bringcenterButtonToFront called...")
        self.view.bringSubview(toFront: self.centerButton);
    }

}

これは、完全なリファレンスのためのDashboardViewControllerです。

class DashboardViewController: BaseViewController, CustomTabBarControllerDelegate
{
    override func viewDidLoad()
    {
        super.viewDidLoad()
        (self.tabBarController as! CustomTabBarController).customTabBarControllerDelegate = self;
    }

    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated);
        (self.tabBarController as! CustomTabBarController).showCenterButton();
    }

    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated);

        self.hidesBottomBarWhenPushed = false;
        (self.tabBarController as! CustomTabBarController).hideCenterButton();
    }

    override func viewWillLayoutSubviews()
    {
        super.viewWillLayoutSubviews();

        if(!isUISetUpDone)
        {
            self.view.backgroundColor = UIColor.lightGray
            self.title = "DASHBOARD"
            self.prepareAndAddViews();
            self.isUISetUpDone = true;
        }
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }

    //MARK: CustomTabBarControllerDelegate Methods

    func customTabBarControllerDelegate_CenterButtonTapped(tabBarController: CustomTabBarController, button: UIButton, buttonState: Bool)
    {
        print("isDrive ON : \(buttonState)");
    }

    //MARK: Internal Methods

    func menuButtonTapped()
    {
        let myFriendsVC = MyFriendsViewController()
        myFriendsVC.hidesBottomBarWhenPushed = true;
        self.navigationController!.pushViewController(myFriendsVC, animated: true);
    }

    //MARK: Private Methods

    private func prepareAndAddViews()
    {
        let menuButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
        menuButton.titleLabel?.text = "Push"
        menuButton.titleLabel?.textColor = UIColor.white
        menuButton.backgroundColor = UIColor.red;
        menuButton.addTarget(self, action: #selector(DashboardViewController.menuButtonTapped), for: .touchUpInside)
        self.view.addSubview(menuButton);
    }
}
6
Vineet