Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UIBarButtonItem With BG Colour and Text Swift 3

I have two buttons on my right of my navigation bar.

extension UIViewController {

func setNavigationBarItem() {

    let profileButton   = UIBarButtonItem(title: "?", style: .plain, target: self, action: #selector(didTapProfileButton(_:)))
    navigationItem.rightBarButtonItems = [addRightBarButtonWithImage(UIImage(named: "menu")!), profileButton]

    self.slideMenuController()?.removeRightGestures()
    self.slideMenuController()?.addRightGestures()
    }
}

I have created 2 buttons like this. But the profileButton I want is with background colour and having corner radius to that button. How to add it to make it look like :

enter image description here

Ignore black part. UIBarButton will be of yellow colour background and corner radius.

like image 900
Nitesh Avatar asked Jan 02 '17 10:01

Nitesh


2 Answers

For that you have only one option you need to create UIButton instance with design that you want after that create UIBarButtonItem instance from that button.

let btnProfile = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
btnProfile.setTitle("SY", for: .normal)
btnProfile.backgroundColor = UIColor.yellow
btnProfile.layer.cornerRadius = 4.0
btnProfile.layer.masksToBounds = true

Now create the UIBarButtonItem from that button and set it with the rightBarButtonItems.

navigationItem.rightBarButtonItems = [addRightBarButtonWithImage(UIImage(named: "menu")!), UIBarButtonItem(customView: btnProfile)]
like image 166
Nirav D Avatar answered Sep 27 '22 19:09

Nirav D


    let profileButton = UIButton()
    profileButton.frame = CGRect(x:0, y:0, width:30, height:30)
    profileButton.setTitle("SY", for: .normal)
    profileButton.setTitle("SY", for: .highlighted)
    profileButton.backgroundColor = UIColor.yellow
    profileButton.layer.cornerRadius = 5.0
    profileButton.addTarget(self, action: #selector(didTapProfileButton(_:)), for: .touchUpInside)

    let rightBarButton = UIBarButtonItem(customView: profileButton)
    self.navigationItem.rightBarButtonItem = rightBarButton
like image 44
Lineesh K Mohan Avatar answered Sep 27 '22 21:09

Lineesh K Mohan