【问题标题】:Getting the text of a particular line on UITextView在 UITextView 上获取特定行的文本
【发布时间】:2012-06-25 11:19:59
【问题描述】:
最后,我想知道 UITextView 中最后一个字符的位置。我能够通过使用以下方法找出 y 位置:
CGSize 大小 = [textView.text
sizeWithFont:textView.font
constrainedToSize:CGSizeMake(textView.frame.size.width-16, 10000)
lineBreakMode:UILineBreakModeClip];
但是,为了获得 x 位置,我需要从 textview 的最后一行获取文本。我尝试从 textView.text 一次删除一个字符,直到 size.height 发生变化以实现该效果,但我意识到这并不总是等于考虑换行符时我想要的。
有什么建议吗?我已经花了一整天的时间试图弄清楚这一点......
【问题讨论】:
标签:
ios
text
uitextview
line
【解决方案1】:
我想我找到了一个解决方案,方法是使用 caretRectForPosition 获取光标在 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】:
您可以像这样评估 uitextview 或 uitextfield 中的文本大小
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);