1

I have programatically created a toolbar to which I have added a UIBarButtonItem.

This is what is currently looks like:

UIBarButtonItem

I want the the button to have a border and a corner radius(curved corners). How will the same be implemented?

UIBarButtonItem Implementation code:

let okBarBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "donePressed:")
Supratik Majumdar
  • 2,365
  • 1
  • 23
  • 31

3 Answers3

6

If you can find the UIView associated with the UIBarButtonItem, you can modify the UIView.layer. But, finding the UIView is not made easy. I used the technique from Figure out UIBarButtonItem frame in window? . Starting with the navigationController.navigationBar, which itself is a UIView, I recursed through the subviews, one of which will be the button I wanted. Which one? Pick your own criteria! Here's my code:

func recurseViews(view:UIView) {
    print("recurseViews: \(view)") // helpful for sorting out which view is which
    if view.frame.origin.x > 700 { // find _my_ button
        view.layer.cornerRadius = 5
        view.layer.borderColor = UIColor.redColor().CGColor
        view.layer.borderWidth = 2
    }
    for v in view.subviews { recurseViews(v) }
}

then in viewDidAppear (or similar)

recurseViews((navigationController?.navigationBar)!)

which is a bit of a hack but does the job:

button with border

Community
  • 1
  • 1
emrys57
  • 6,679
  • 3
  • 39
  • 49
  • Normally I try to stay away from using tags but this is one of those cases where assigning a tag and traverse the view hierarchy for it makes sense so you can get the specific view more reliably. – jusynth Apr 03 '17 at 04:21
1

There's no built-in automatic way to do this, unfortunately. You have two choices:

  • You could make this a bar button item with a custom view, make that view a UIButton, and then do the usual stuff to that UIButton (which you can do because it's a view), by way of its layer (give it a border and corner radius).

  • You could just draw (in code) a background image with a curved border and use that as the bar button item's image.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

I do it with a storyboard. Just add UIButton inside UiBarButtonItem. Like here enter image description here

And after that added a border to the UIButton
enter image description here

Vladyslav Panchenko
  • 1,517
  • 1
  • 19
  • 23