我正在设置一个图像为酒吧按钮项目,我有一个像:
分辨率为30 * 30,但是我将此图像分配给条形按钮,其外观如下所示:
我以这种方式分配了图像:
并且如果我尝试这样的方式像制作一个IBOutlet的按钮,并设置图像编程从this问题和代码为:
// Outlet for bar button @IBOutlet weak var fbButton: UIBarButtonItem! // Set Image for bar button var backImg: UIImage = UIImage(named: "fb.png")! fbButton.setBackgroundImage(backImg,forState: .Normal,barMetrics: .Default)
但没有发生这个,
有人可以告诉我我做错了什么吗?
或者是这样做的糊口?
我已经通过以下代码实现了这一点:
原文链接:https://www.f2er.com/swift/320387.htmlimport UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //create a new button let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton //set image for button button.setImage(UIImage(named: "fb.png"),forState: UIControlState.Normal) //add function for button button.addTarget(self,action: "fbButtonPressed",forControlEvents: UIControlEvents.TouchUpInside) //set frame button.frame = CGRectMake(0,53,31) let barButton = UIBarButtonItem(customView: button) //assign button to navigationbar self.navigationItem.rightBarButtonItem = barButton } //This method will call when you press button. func fbButtonPressed() { println("Share to fb") } }
结果将是:
同样的方式,您也可以通过这种方式设置左侧的按钮:
self.navigationItem.leftBarButtonItem = barButton
结果将是:
如果您想要与导航控制器相同的事务,当您返回使用默认返回按钮,那么您可以使用此代码使用自定义后退按钮实现:
func backButtonPressed(sender:UIButton) { navigationController?.popViewControllerAnimated(true) }
对于swift 3.0:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //create a new button let button = UIButton.init(type: .custom) //set image for button button.setImage(UIImage(named: "fb.png"),for: UIControlState.normal) //add function for 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 to navigationbar self.navigationItem.rightBarButtonItem = barButton } //This method will call when you press button. func fbButtonPressed() { print("Share to fb") } }