简体   繁体   中英

How to count number of lines in UITextField?

I need to count number of lines in my UITextField .

My UITextField has an array of UIBezierPath , to draw text along an UIImage .

UIBezierPath *rect = [UIBezierPath bezierPathWithRoundedRect:_image.frame cornerRadius:0];
[_txt addSubview:_image];
_txt.textContainer.exclusionPaths = @[rect];

Obviously, number of lines is different because there is an exclusion path and this common way,

 CGSize size  = [_txt.text
                sizeWithFont:_txt.font constrainedToSize:(CGSize){_txt.frame.size.width, INTMAX_MAX}
                lineBreakMode:NSLineBreakByWordWrapping];

returns a wrong result.

Note: _txt is an UITextField .

thanks.


Test case:

在此处输入图片说明

Ref: http://goo.gl/Ch9al6

In UITextInputProtocol there's a method there called firstRectForRange: ( doc here ). This might do the trick. Try it with a text range set to the end of the backing string.

// given a UITextView* called textView
UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *p0 = [textView positionFromPosition:beginning offset:textView.text.length-1];
UITextPosition *p1 = [textView positionFromPosition:p0 offset:1];
UITextRange *textRange = [textView textRangeFromPosition:p0 toPosition:p1];
CGRect rect = [textView firstRectForRange:textRange];
// rect will be given in the coordinate space of textView

Disclaimer: I haven't tried this even for a simple case, and yours looks non-trivial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM