为栏button项目设置图像和标题?

我目前有一个自定义的导航控制器与栏button项目,只是文本button。 是否可以保留酒吧button项目的标题,但也可以将其设置为图像(图标图像+下面的标题)。

class NavigationController: UINavigationController { var mode: NavigationMode = .Swipe { didSet { self.setButtonAttributes() } } private var leftBarButton: UIBarButtonItem! private var middleBarButton: UIBarButtonItem! private var rightBarButton: UIBarButtonItem! private var rightBarButton2: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() } func configureNavigationItem(navigationItem: UINavigationItem) { //Configure the bar buttons text and actions if (self.leftBarButton == nil) { self.leftBarButton = UIBarButtonItem(title: "Menu1", style: .Plain,target: self, action: "menu1Pressed:") } if (self.middleBarButton == nil) { self.middleBarButton = UIBarButtonItem(title: "Games", style: .Plain, target: self, action: "gamesPressed:") } if (self.rightBarButton == nil) { self.rightBarButton = UIBarButtonItem(title: "Menu3", style: .Plain, target: self, action: "menu3Pressed:") } if (self.rightBarButton2 == nil) { self.rightBarButton2 = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: "settingsPressed:") } self.setButtonAttributes() navigationItem.leftBarButtonItems = [self.leftBarButton, self.middleBarButton, self.rightBarButton, self.rightBarButton2] } 

更新:

  let button = UIButton(type: .System) button.setImage(UIImage(named: "play"), forState: .Normal) button.setTitle("Play", forState: .Normal) button.sizeToFit() leftBarButton = UIBarButtonItem(customView: button) if (self.leftBarButton == nil) { self.leftBarButton = UIBarButtonItem(title: "Play", style: .Plain,target: self, action: "Pressed:") } 

您可以创buildUIButton实例,为其设置图像和标题,然后使用它创build您的UIBarButtonItem:

  let button = UIButton(type: .System) button.setImage(UIImage(named: "YourImage"), forState: .Normal) button.setTitle("YourTitle", forState: .Normal) button.sizeToFit() self.leftBarButton = UIBarButtonItem(customView: button) 

要添加一个动作:

  button.addTarget(self, action: #selector(self.someAction), forControlEvents: .TouchUpInside) 

self.someAction是

 func someAction() { } 

Swift 3:

  let button = UIButton(type: .system) button.setImage(UIImage(named: "categories_icon"), for: .normal) button.setTitle("Categories", for: .normal) button.addTarget(self, action: #selector(showCategories), for: .touchUpInside) button.sizeToFit() self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)