Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change width of a UIBarButtonItem in a UINavigationBar in swift

Tags:

swift

ios7

i need to set frame for my navigation bar button in swift 2.0

i tried this code

self.navigationController!.navigationBar.drawRect(CGRectMake(0, 0, 30, 30)) 

but it won't work

thanks in advance

like image 566
Muruganandam Sathasivam Avatar asked Jan 20 '16 05:01

Muruganandam Sathasivam


3 Answers

// Swift 3
let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
backButton.setBackgroundImage(UIImage(named: "img"), for: .normal)
backButton.addTarget(self, action: "action:", for: .touchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)

// Swift 2
let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
backButton.setBackgroundImage(UIImage(named: "img"), forState: .Normal)
backButton.addTarget(self, action: "action:", forControlEvents: .TouchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
like image 146
Sai Li Avatar answered Nov 08 '22 19:11

Sai Li


    // We dont have  Property to change UIBarButtonItem frame
    // So we can creat UIButton() and give requered frame and add to navigationItem.setLeftBarButtonItems
    // Please refere Belove code

    // Swift 2.0

    let btnBack   = UIButton()
    btnBack.frame = CGRectMake(0, 0, 100, 64)
    btnBack.addTarget(self, action: "backAction", forControlEvents: UIControlEvents.TouchUpInside)
    let leftBarBackBtn: UIBarButtonItem = UIBarButtonItem(customView: btnBack)
    self.navigationItem.setLeftBarButtonItems([ leftBarBackBtn ], animated: false)

    // Please submit your answer with Explanation comments to improve your Quality or Answer and question
like image 22
Vinayak Avatar answered Nov 08 '22 19:11

Vinayak


the top answer for swift 3:

 let homeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
 homeButton.setBackgroundImage(#imageLiteral(resourceName: "home-1"), for: .normal)
 homeButton.addTarget(self, action: #selector(homePressed), for: .touchUpInside)
 self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: homeButton)
like image 26
Daniel Jones Avatar answered Nov 08 '22 21:11

Daniel Jones