如何限制UITextView中的行数? [英] How to limit the number of lines in UITextView?

查看:663
本文介绍了如何限制UITextView中的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的屏幕上有一个UITextView,用户只应填写两行,当第二行中的用户返回键应变为完成

I have a UITextView in my screen, the user should fill only two lines, and when the user in the second line the return key should turn into Done.

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

How can I limit the number of lines in UITextView? I searched a lot, and no results was useful!

我找到了Swift的答案:

I found this answer for Swift:

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

它没有'通过这种方式,用户可以输入无限字符,但在屏幕上查看的内容只有两行!

It didn't work, by this way the user can enter infinity character, but what viewed on the screen are just two lines!

所以如果你试图打印textView文本你将找到灾难文本。

So if you tried to print the text of textView you will find a disaster text.

推荐答案

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

You need to implement textView:shouldChangeTextInRange:replacementText:. This method is called whenever the text is going to change. You can access the current content of the text view using its text property.

使用 [textView.text stringByReplacingCharactersInRange:range withString:replacementText] 。

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

You can then count the number of lines and return YES to allow the change or NO to reject it.

编辑:在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;
}

这篇关于如何限制UITextView中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆