leroy guo leroy guo - 4 months ago 40
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.


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