在uitextview中获取字符串的结尾

时间:2015-06-27 19:11:25

标签: ios height uilabel uitextview xib

我想创建一个消息框,就像Telegram和其他聊天一样,在盒子的下方有一段时间。

但是如果文本在行的末尾结束,则时间标签应该在下一行中,否则,应该保持在同一行。

所以,我想要这样的东西: new line for date when content is goes until the end

如何在我的xib中以编程方式完成此操作?

谢谢你,

1 个答案:

答案 0 :(得分:1)

您可以计算文本视图中最后一个字符的位置,并检查时间标签是否有足够的空间然后显示,否则将其添加到新行。

UITextPosition *Pos2 = [textView positionFromPosition:textView.endOfDocument offset:0];
UITextPosition *Pos1 = [textView positionFromPosition:textView.endOfDocument offset:-1];
UITextRange *range = [textView textRangeFromPosition:Pos1 toPosition:Pos2];
CGRect lastCharRect = [textView firstRectForRange:(UITextRange *)range];
CGFloat freeSpace = textView.frame.size.width - lastCharRect.origin.x - lastCharRect.size.width;
if (freeSpace > requiredWidthForTimeLabel) {
    //add time label to the last line     
} else {
    //add time label on a new line
}