Perry Hoekstra
Perry Hoekstra

Reputation: 2763

Get the View of UIBarButtonItem in Swift

Hopefully, this is an easy question. I am trying to obtain the UIView of a UIBarButtonItem. Looking at the following StackOverflow question I came up with the following code:

let notificationButton = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil)

let notificationView = notificationButton.value(forKey: "view") as? UIView

However, notificationView is nil. So, thoughts on what I failed to interpret from the linked StackOverflow question?

Upvotes: 3

Views: 4183

Answers (2)

Serj Rubens
Serj Rubens

Reputation: 638

Starting from iOS 11 this code will not work cause line of code below will not cast UIView. Also it's counting as private API and seems to be will not pass AppStore review.

guard let view = self.value(forKey: "view") as? UIView else { return } 

Thread on: forums.developer.apple

Upvotes: 3

Perry Hoekstra
Perry Hoekstra

Reputation: 2763

So, DS Dharma gave me a idea which ended up working. The "view" value is only available after it is assigned to the toolbar navigation item like this:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil)

self.navigationItem.rightBarButtonItem?.addBadge(number: 0, withOffset: CGPoint(x: 7.0, y: 0.0) , andColor: UIColor.black, andFilled: true)

where the addBadge() function needs the UIView. BTW, if anyone is wondering, the addBadge function was taken from this post: http://www.stefanovettor.com/2016/04/30/adding-badge-uibarbuttonitem

Highly recommended if you need this piece of functionality.

Upvotes: 1

Related Questions