我正试图像这样访问UIBarButtonItem
的框架:
if let items = self.toolbarItems{
let item = items[1]
print(item)
let view = item.value(forKey: "view") as! UIView
}
print(item)返回现有项目。为什么不能让UIView
回来?
答案 0 :(得分:5)
使用未记录的属性存在问题。他们可以更改,恕不另行通知。
以下是使用Xcode 8.3.1使用iOS 10 SDK的结果。
let item1 = UIBarButtonItem(customView: UIView())
let view1 = item1.value(forKey: "view") as? UIView
print("\(view1)")
打印
Optional(<UIView: 0x7f9049001400; frame = (0 0; 0 0); layer = <CALayer: 0x60000003cc00>>)
然而
let item2 = UIBarButtonItem(title: "Test", style: .plain, target: nil, action: nil)
let view2 = item2.value(forKey: "view") as? UIView
print("\(view2)")
打印
nil
即使把它提升到新的水平
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)")
打印
nil