设置最大行可编辑TextView - Swift / iOS

时间:2017-06-25 20:38:16

标签: ios swift uitextview

以下代码将设置TextView的最大行数。

textView.textContainer.maximumNumberOfLines = 5;
textView.textContainer.lineBreakMode = .byTruncatingTail

但是,在编辑模式下,您可以按住输入超出最大线数并键入屏幕。

如果您尝试输入更多内容,如何使光标不会转到下一行?

1 个答案:

答案 0 :(得分:0)

试试这个

func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize {
    return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
        options: NSStringDrawingOptions.UsesLineFragmentOrigin,
        attributes: [NSFontAttributeName: font],
        context: nil).size
}


func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
    var textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset))
    textWidth -= 5.0 * textView.textContainer.lineFragmentPadding;

    let boundingRect = sizeOfString(newText, constrainedToWidth: Double(textWidth), font: textView.font!)
    let numberOfLines = boundingRect.height / textView.font!.lineHeight;

    return numberOfLines <= 5;
}