How to apply borders and corner radius to UIBarButtonItem?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-09 14:14:27

问题


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

This is what is currently looks like:

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:")

回答1:


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:




回答2:


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.



来源:https://stackoverflow.com/questions/35611106/how-to-apply-borders-and-corner-radius-to-uibarbuttonitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!