Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom view on right of navigation bar Swift?

I am trying to add a custom view on right of UINavigationBar. What I tried is the following, but the view is not showing up! Please help, thanks in advance!

let viewOnrightButton = UIView(frame: CGRect(x: 2, y: 2, width: 60, height: 22))
 // viewOnrightButton.frame = CGRectMake(2, 2, 60, 22)
viewOnrightButton.layer.cornerRadius = 2
viewOnrightButton.backgroundColor = UIColor(red: 0.961, green: 0.827, blue: 0.239, alpha: 1.00)

lblNumbersOfBanana.frame = CGRectMake(2, 1, viewOnrightButton.frame.width-20, 20)
lblNumbersOfBanana.text = "001"

var bananaImgView = UIImageView(frame: CGRect(x: viewOnrightButton.frame.width-22, y: 0, width: 20, height: 20))
 //  bananaImgView.frame = CGRectMake(viewOnrightButton.frame.width-22, 0, 20, 20)
bananaImgView.image = UIImage(named: "banana")

viewOnrightButton.addSubview(lblNumbersOfBanana)
viewOnrightButton.addSubview(bananaImgView)

self.navigationItem.rightBarButtonItem?.customView = viewOnrightButton
like image 577
dip Avatar asked Aug 07 '15 10:08

dip


People also ask

How do I customize the navigation bar in Swift?

Start with Navigation ControllerCreate a single view application in Xcode. Add two view controller into your storyboard. Create two different swift files for those view controllers and set identifiers for them. Take a button in each view controller, set constrain for them and customize as you want.


2 Answers

You can do like this, try it:

var view = UIView(frame: CGRectMake(0, 0, 100, 44))
view.backgroundColor = UIColor.yellowColor()
var barButtonItem = UIBarButtonItem(customView: view)
self.navigationItem.rightBarButtonItem = barButtonItem
like image 153
iAnurag Avatar answered Oct 09 '22 20:10

iAnurag


Swift 3/4/5 Version of the Accepted Answer

let viewFN = UIView(frame: CGRect.init(x: 0, y: 0, width: 180, height: 40))
viewFN.backgroundColor = .yellow
let button1 = UIButton(frame: CGRect.init(x: 0, y: 0, width: 40, height: 20))
button1.setImage(UIImage(named: "notification"), for: .normal)
button1.setTitle("one", for: .normal)

button1.addTarget(self, action: #selector(self.didTapOnRightButton), for: .touchUpInside)
let button2 = UIButton(frame: CGRect.init(x: 40, y: 8, width: 60, height: 20))
button2.setImage(UIImage(named: "notification"), for: .normal)
button2.setTitle("tow", for: .normal)
let button3 = UIButton(frame: CGRect.init(x: 80, y: 8, width: 60, height: 20))
button3.setImage(UIImage(named: "notification"), for: .normal)
button3.setTitle("three", for: .normal)

button3.addTarget(self, action: #selector(self.didTapOnRightButton), for: .touchUpInside)

viewFN.addSubview(button1)
viewFN.addSubview(button2)
viewFN.addSubview(button3)

let rightBarButton = UIBarButtonItem(customView: viewFN)

Hope it helps someone. Cheers!

like image 30
Md. Ibrahim Hassan Avatar answered Oct 09 '22 22:10

Md. Ibrahim Hassan