I am using a splitViewController to enable a slide out menu in my app, using Swift on iOS 9.
I have everything working as desired except that I cannot get a custom image for my "Menu" button (which is the splitViewController's displayModeButtonItem).
Here is what I have tried.
override func viewDidLayoutSubviews() {
// This will create a properly-working menu barbuttonitem, but is of course
// a text based title.
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "≡",
style: UIBarButtonItemStyle.Plain,
target: splitViewController!.displayModeButtonItem().target,
action: splitViewController!.displayModeButtonItem().action)
This version is my attempt to use a custom image instead of a text title, but I just get a gray box where the image should be.
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "29x29"),
style: .Plain,
target: splitViewController!.displayModeButtonItem().target,
action: splitViewController!.displayModeButtonItem().action)
Any suggestions?
Thanks
You'll want to make a UIButton
and set the image in it and set that as a leftBarButtonItem like so in your -viewDidLoad
:
let menuButton = UIButton(type: .Custom)
menuButton.frame = CGRectMake(0, 0, 29, 29)
menuButton.setImage(UIImage(named:"29x29"), forState: .Normal)
menuButton.addTarget(self, action: "menuPressed:", forControlEvents: .TouchUpInside)
let barButton = UIBarButtonItem(customView: menuButton)
navigationItem.leftBarButtonItem = barButton
and in a separate method, perform your action:
func menuPressed(sender: AnyObject) {
//show menu
}