Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add border in UIBarButtonItem

In my app, I have designed a view in the interface builder.
This view has a toolbar, with some UIBarButtonItem in.

My buttons can be custom images, or default button like share, add,...
Now with iOS7, buttons don't have anymore borders. So I'd like to add some. enter image description here

Here is what i want to do : add borders like the white lines on my screenshot. What I've tried is to add a UIButton to the toolbar. In my example, I've set my back button size (12x44). I add this button as a IBOutlet property of my view controller, and try to draw a border to it :

CALayer *cancelBorder = [CALayer layer];
[cancelBorder setFrame:CGRectMake(12, 0, 1, 44)];
[backBorder setBackgroundColor:[[UIColor whiteColor] CGColor]];
[backButton.layer addSublayer:cancelBorder];

But it doesn't work. Anyone has a solution?

like image 429
zbMax Avatar asked Sep 26 '13 16:09

zbMax


2 Answers

Adding UIBarButtonItem to toolbar programmatically may solve your problem.

First, create custom button with images, borders, etc. As HereTrix said, you can add border to this button.

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10, 0, 30, 30);
button.layer.borderColor = [UIColor blueColor].CGColor;
button.layer.borderWidth = 1.0f;
/* any other button customization */

Then, initialize UIBarButtonItem with that custom button and add this item to your toolbar.

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.toolBar.items = @[backButton];
like image 81
caglar Avatar answered Oct 21 '22 05:10

caglar


Swift 3 : Below is my full implementation for button customization and event handling.

Test UIBarButtonItem

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton.init(type: .custom)
    button.setTitle("Tester", for: .normal)
    button.setTitleColor(.darkGray, for: .normal)
    button.layer.borderWidth = 1
    button.layer.cornerRadius = 5
    button.layer.borderColor = UIColor.darkGray.cgColor
    button.addTarget(self, action: #selector(self.handleButton), for: .touchUpInside)

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let button = self.navigationItem.rightBarButtonItem?.customView {
        button.frame = CGRect(x:0, y:0, width:80, height:34)
    }
}

func handleButton( sender : UIButton ) {
    // It would be nice is isEnabled worked...
    sender.alpha = sender.alpha == 1.0 ? 0.5 : 1.0
}

Hope this helps

like image 33
Joe Andolina Avatar answered Oct 21 '22 04:10

Joe Andolina