Anchor a popover to the rect of a selected textRange in textView iOS

360 views Asked by At

I'm trying to present a popover from a UIMenuItem which anchor point is the rect of a selected text in a textView. I have the following code:

func pickColor(sender: UIMenuItem) {
    let range = noteTextView.selectedTextRange
    let beginningOfSelection = noteTextView.caretRect(for: (range?.start)!)
    let endOfSelection = noteTextView.caretRect(for: (range?.end)!)

    let storyboard: UIStoryboard = UIStoryboard(name: "ColorPicker", bundle: nil)
    let colorVC = storyboard.instantiateViewController(withIdentifier: "ColorPickerViewController") as UIViewController
    colorVC.modalPresentationStyle = .popover
    let popover: UIPopoverPresentationController = colorVC.popoverPresentationController!
    popover.sourceView = noteTextView
    popover.sourceRect = CGRect(x: (beginningOfSelection.origin.x + endOfSelection.origin.x)/2, y: (beginningOfSelection.origin.y + beginningOfSelection.size.height)/2, width: 0, height: 0)
    present(colorVC, animated: true, completion: nil)
}

The app crashes in the line colorVC.modalPresentationStyle = .popover. Can someone tell me what's going on here? Thanks! :)

0

There are 0 answers