6
votes

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?

2
Your cancelBorder may be out of the bounds of your backButton. You said your backButton has a width of 12, and your cancelBorder has an x-offset of 12. So the cancelBorder begins outside of the bounds of your backButton and therefor won't be visible(assuming the button has clipToBounds = YES, which i think it hast). Maybe try it with an offset of 8 or something and look if it's visible. For being at the edge it then has to be an offset of 11.manuelwaldner

2 Answers

10
votes

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];
7
votes

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