ios - How to set image for bar button with swift? -
i trying set image bar button item have image like:
with resolution 30 * 30 while assign image bar button looks like:
i have assigned image way :
and if try way making iboutlet button , set image programatically form this question , code is:
// outlet bar button @iboutlet weak var fbbutton: uibarbuttonitem! // set image bar button var backimg: uiimage = uiimage(named: "fb.png")! fbbutton.setbackgroundimage(backimg, forstate: .normal, barmetrics: .default)
but nothing happend this,
can tell me doing wrong?
or batter way this?
i have achieved programatically code:
import uikit class viewcontroller: uiviewcontroller { override func viewdidload() { super.viewdidload() //create new button let button: uibutton = uibutton.buttonwithtype(uibuttontype.custom) as! uibutton //set image button button.setimage(uiimage(named: "fb.png"), forstate: uicontrolstate.normal) //add function button button.addtarget(self, action: "fbbuttonpressed", forcontrolevents: uicontrolevents.touchupinside) //set frame button.frame = cgrectmake(0, 0, 53, 31) let barbutton = uibarbuttonitem(customview: button) //assign button navigationbar self.navigationitem.rightbarbuttonitem = barbutton } //this method call when press button. func fbbuttonpressed() { println("share fb") } }
and result be:
same way can set button left side way:
self.navigationitem.leftbarbuttonitem = barbutton
and result be:
and if want same transaction navigation controller have when go default button can achieve custom button code:
func backbuttonpressed(sender:uibutton) { navigationcontroller?.popviewcontrolleranimated(true) }
for swift 3.0:
import uikit class viewcontroller: uiviewcontroller { override func viewdidload() { super.viewdidload() //create new button let button = uibutton.init(type: .custom) //set image button button.setimage(uiimage(named: "fb.png"), for: uicontrolstate.normal) //add function button button.addtarget(self, action: #selector(viewcontroller.fbbuttonpressed), for: uicontrolevents.touchupinside) //set frame button.frame = cgrect(x: 0, y: 0, width: 53, height: 51) let barbutton = uibarbuttonitem(customview: button) //assign button navigationbar self.navigationitem.rightbarbuttonitem = barbutton } //this method call when press button. func fbbuttonpressed() { print("share fb") } }
Comments
Post a Comment