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;
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...