Raw*_*wan 10 uitextview ios swift
我的屏幕上有一个UITextView,用户应该只填充两行,当用户在第二行时,返回键应该变为Done.
如何限制UITextView中的行数?我搜索了很多,没有结果有用!
我找到了Swift的答案:
locationNoteTextView.textContainer.maximumNumberOfLines = 2
self.locationNoteTextView.textContainer.lineBreakMode = NSLineBreakMode.ByClipping
Run Code Online (Sandbox Code Playgroud)
它不起作用,通过这种方式用户可以输入无限字符,但在屏幕上查看的只是两行!
因此,如果您尝试打印textView文本,您将找到灾难文本.
Abh*_*nav 17
你需要实施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;
}
Run Code Online (Sandbox Code Playgroud)
Rah*_*ule 13
适用于iOS 7+
textView.textContainer.maximumNumberOfLines = 10;
textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
Run Code Online (Sandbox Code Playgroud)
要么
textView.textContainer.maximumNumberOfLines = 10;
[textView.layoutManager textContainerChangedGeometry:textView.textContainer];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15452 次 |
| 最近记录: |