如果有人需要斯威夫特代碼接受的答案:
let infoImage = UIImage(named: "my-icon-32.png")
let imgWidth = infoImage?.size.width
let imgHeight = infoImage?.size.height
let button:UIButton = UIButton(frame: CGRect(x: 0,y: 0,width: imgWidth!, height: imgHeight!))
button.setBackgroundImage(infoImage, forState: .Normal)
button.addTarget(self, action: Selector("openInfo"), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
附: Gurpreet Singh答案只適用於透明PNG,我還必須設置除clearColor以外的按鈕tintcolor。
來源
2014-11-20 12:15:08
Aks
它的偉大工程,但是當我在按鈕上單擊應用程序崩潰是和仿真器突然退出。 – 2011-05-09 08:17:52
我該怎麼做,不要失去在故事板中定義到按鈕的塞格動作? – 2013-08-02 13:31:59
Renato:給這個segue一個名字,並且在按鈕的目標動作中調用'[self performSegueWithIdentifier:@「yourSegueName」sender:self];'' – lari 2013-08-06 12:20:40