0

Is there a way to attach a UITextField inside inside the range of an NSAttributedString that is inside a UITextView?

I want to recreate something like this:

enter image description here

Where the user would be able to press the empty lines to type text.

danywarner
  • 928
  • 2
  • 15
  • 28

1 Answers1

0

You could calculate a frame for the UITextField like so:

- (CGRect)textFieldFrameForCharacterRange:(NSRange)charRange inTextView:(UITextView *)textView {
    NSRange glyphRange = [textView.layoutManager glyphRangeForCharacterRange:charRange actualCharacterRange:NULL];
    CGRect boundingRect = [textView.layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textView.textContainer];
    return boundingRect;
}

and then add it as a subview of the UITextView. Determining a character range to pass to the above method can be easy too - just search for a run of underlines, or maybe a custom attribute using - enumerateAttribute:inRange:options:usingBlock:.

The catch is this won't work properly if the underlines are split into more than one line, but UITextField wouldn't fit that case anyway. So you need a way to make sure the underline remains unbroken. The U+2060 unicode character may help, see Prevent line break in a NSAttributedString for more. An NSTextAttachment with the underline represented as an image would also be guaranteed not to get word wrapped.

Alternatively, you could implement a UITextViewDelegate, or possibly even a UITextView subclass, that disallows selection and editing outside of the underline ranges. That way you can avoid the weirdness of UITextFields within UITextViews. But the drawback with this method is even if you deleted an underline character every time the user types a character, the user would still see the overall length of the underline fluctuating slightly.

Community
  • 1
  • 1