3

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?

Perry Hoekstra
  • 2,687
  • 3
  • 33
  • 52

2 Answers2

3

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

Serj Rubens
  • 621
  • 8
  • 12
1

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.

Perry Hoekstra
  • 2,687
  • 3
  • 33
  • 52
  • Unfortunately this doesn't work when you have multiple bar items. e.g. self.navigationItem.rightBarButtomItems.append(barBtn) – azm882 Nov 30 '17 at 19:13