Check if text in UITextView went to new line due to word wrap

喜夏-厌秋 提交于 2019-12-22 10:58:45

问题


How can I check if the text in a UITextView went to the next line due to word wrap?

I currently have code to check if the user enters a new line (from the keyboard).

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
    if ( [text isEqualToString:@"\n"] ) {
        ...
    }
    return YES;
}

回答1:


You can use the contentSize.height property of UITextView to determine how 'tall' your textview is. You can then divide by the lineHeight to figure out the number of lines. @nacho4d provided this nifty line of code that does just that:

int numLines = textView.contentSize.height/textView.font.lineHeight;

Refer to this question for more info: How to read number of lines in uitextview

EDIT: So you could do something like this inside -textViewDidChange: in order to check for a line change.

int numLines = textView.contentSize.height / textView.font.lineHeight; 
if (numLines != numLinesInTextView){
    numLinesInTextView = numLines;//numLinesInTextView is an instance variable
    //then do whatever you need to do on line change
}


来源:https://stackoverflow.com/questions/29111193/check-if-text-in-uitextview-went-to-new-line-due-to-word-wrap

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