4

I am trying to access the frame of a UIBarButtonItem like this:

if let items = self.toolbarItems{

        let item = items[1]

        print(item)
        let view = item.value(forKey: "view") as! UIView


    }

print(item) returns an existing item. Why is it not possible to get an UIView back?

JVS
  • 2,592
  • 3
  • 19
  • 31
  • 1
    `UIBarButtonItem` isn't a view. – rmaddy Apr 26 '17 at 18:21
  • http://stackoverflow.com/questions/28991100/get-the-frame-of-uibarbuttonitem-in-swift – Tushar Sharma Apr 26 '17 at 18:22
  • @rmaddy this is why i access item.value(forKey: "view") – JVS Apr 26 '17 at 18:23
  • @TusharSharma this is the sample code I used – JVS Apr 26 '17 at 18:24
  • No, you didn't use the code from the mentioned link. It should look like this: `let barButtonItem = self.navigationItem.rightBarButtonItem! let buttonItemView = barButtonItem.value(forKey: "view") as? UIView let buttonItemSize = buttonItemView?.frame.size` – kamil3 Apr 26 '17 at 18:45
  • @kamil3 I was referring to item.value(forKey:"view") as! UIView. it is the same. the rest is ignorable since it isn't the issue. – JVS Apr 27 '17 at 07:49

1 Answers1

5

That's the problem with using undocumented properties. They can change without notice.

Here are the results using Xcode 8.3.1 using the iOS 10 SDK.

let item1 = UIBarButtonItem(customView: UIView())
let view1 = item1.value(forKey: "view") as? UIView
print("\(view1)")

prints

Optional(<UIView: 0x7f9049001400; frame = (0 0; 0 0); layer = <CALayer: 0x60000003cc00>>)

However

let item2 = UIBarButtonItem(title: "Test", style: .plain, target: nil, action: nil)
let view2 = item2.value(forKey: "view") as? UIView
print("\(view2)")

prints

nil

Even taking this to the next level

class MyObject: NSObject { @objc var view: UIView? } // Fake to get selector

let item3 = UIBarButtonItem(title: "Test", style: .plain, target: nil, action: nil)
let view3 = (item3 as NSObjectProtocol).perform(#selector(getter: MyObject.view))?.takeRetainedValue()
print("\(view3)")

prints

nil
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • 2
    thanks for Your explanation. However, do You know how to fix this issue in my case? I still need to access the frame. – JVS Apr 27 '17 at 07:50