ios – 如何限制UITextView中的行数?

我的屏幕上有一个UITextView,用户应该只填充两行,当用户在第二行时,返回键应该变为Done.

如何限制UITextView中的行数?
搜索了很多,没有结果有用!

我找到了Swift的答案:

locationNoteTextView.textContainer.maximumNumberOfLines = 2
self.locationNoteTextView.textContainer.lineBreakMode = NSLineBreakMode.ByClipping

它不起作用,通过这种方式用户可以输入无限字符,但在屏幕上查看的只是两行!

因此,如果您尝试打印textView文本,您将找到灾难文本.

解决方法

您需要实现textView:shouldChangeTextInRange:replacementText:.只要文本发生变化,就会调用方法.您可以使用其text属性访问文本视图的当前内容.

使用[textView.text stringByReplacingCharactersInRange:range withString:replacementText]从传递的范围和替换文本构造新内容.

然后,您可以计算行数并返回YES以允许更改,或者NO拒绝它.

编辑:在OP请求:

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 -= 2.0 * textView.textContainer.lineFragmentPadding;

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

    return numberOfLines <= 2;
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...