leroy guo leroy guo - 1 year ago 157
Swift Question

UIBarButtonItem value(forKey: key) cannot get view any more

I'v used this code to get frame of a uibarbuttonitem:

popoverPC.sourceRect = ((mybarbuttonitem.value(forKey:"view") as AnyObject).frame)!

and it worked well in swift 2.

Now, after I update my code to swift 3, my app crashed with error: unexpectedly found nil while unwrapping an Optional value. Please help.

Answer Source

Unfortunately, you can't use value(forKey:) to do that anymore :(

Assuming that your popoverPC is a UIPopoverPresentationController, you can use the barButtonItem property to set the anchor of the popover:

popoverPC.barButtonItem = mybarbuttonitem
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download