0

Question Using breakpoints, I found that filterBarButton is not nil, but the filterBarButton?.value(forKey: "view")is nil. The filterBarButton should have a view because I assigned it to a button in the viewDidLoad. Why is this happening? How do I fix this?

I use the frame of right bar button (the Filter button) to place the triangle image underneath it as shown below. I want the triangle image to be centered and directly underneath the Filter button. enter image description here

Code

override func viewDidLoad() {
        let filterButton = UIBarButtonItem(title: "Filter", style: .plain, target: self, action: #selector(filterButtonTapped))
        navigationController?.navigationBar.topItem?.rightBarButtonItem = filterButton
        setUpFilter()
    }

func setUpFilter() {
     let filterBarButton = navigationController?.navigationBar.topItem?.rightBarButtonItem
     let btnView = filterBarButton?.value(forKey: "view") as AnyObject
}

Reference

Alex
  • 2,369
  • 3
  • 13
  • 23
  • 1
    No, you never assign a view to the bar button item. Why are you trying to did into the private properties of `UIBarButtonItem`? What is your goal? – rmaddy Nov 29 '17 at 23:56
  • I thought I did? In the `viewDidLoad`, `navigationController?.navigationBar.topItem?.rightBarButtonItem = filterButton` – Alex Nov 30 '17 at 00:06
  • I use the bar button item frame to place an image in the nav bar – Alex Nov 30 '17 at 00:07
  • That assigns a UIBarButtonItem to the navbar. That it no way creates a view in the bar button item itself. – rmaddy Nov 30 '17 at 00:08
  • 1
    If you want to add an image then use `UIBarButtonItem(image:style:target:action:)` and add that button to the nav bar. – rmaddy Nov 30 '17 at 00:09
  • @rmaddy I think you misinterpreted what I meant. I updated my answer to clarify! – Alex Nov 30 '17 at 00:20
  • 1
    The only valid way to get a view from a `UIBarButtonItem` is to create the button using a `customView`. Then you can get that view's frame translated to the navbar's frame. – rmaddy Nov 30 '17 at 00:22
  • okay got it thanks! – Alex Nov 30 '17 at 00:25

0 Answers0