Getting the text of a particular line on UITextView

为君一笑 提交于 2019-12-08 13:09:05

问题


Ultimately, I would like to know the position of the last character in a UITextView. I was able to find out the y position by using the following:

CGSize size = [textView.text sizeWithFont:textView.font constrainedToSize:CGSizeMake(textView.frame.size.width-16, 10000) lineBreakMode:UILineBreakModeClip];

However in order to get the x position I need to get the text from the last line in the textview. I tried removing a character at a time from textView.text until size.height changes to achieve that effect, but I realize that does not always equal to what I want when linebreak is taken into consideration.

Any suggestions anyone? I've been spending a whole day trying to figure this one out...


回答1:


I think I found a solution by using caretRectForPosition to get the pixel position of the cursor in the textview.

// move cursor to the end of the text
textView.selectedRange = NSMakeRange([textView.text length], 0);
CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin;



回答2:


you can evaluate the text size in a uitextview or uitextfield like this

    UIFont * myFont = [UIFont fontWithName:@"Gill Sans" size:19];
    CGSize textSize = [@"your text" sizeWithFont: myFont constrainedToSize:CGSizeMake(textFiled.frame.size.width, textFiled.frame.size.height) lineBreakMode:UILineBreakModeWordWrap];
    NSlog(@"this is your text size W=%f H=%f",textSize.width, textSize.height);



来源:https://stackoverflow.com/questions/11188363/getting-the-text-of-a-particular-line-on-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!