iPhone:限制UITextView中的文本输入 [英] iPhone: Limiting text input in an UITextView

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

问题描述

我试图限制用户可以在UITextView中使用的LINES数量.让我们考虑一下我只想允许4行(即在以下示例中,在给定的UITextView中,宽度为200的情况下,给定字体的高度不能超过84像素).

I am trying to limit the amount of LINES a user can have in an UITextView. Let's consider I only want to allow 4 lines (i.e. in the following example, you can't go higher than a height of 84 pixels with the given font in a given UITextView with a width of 200).

我对此进行了编码以实现限制,并且效果很好:

I coded this to achieve the limiting and it works fine:

    - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText {

    NSString* newText = [aTextView.text stringByReplacingCharactersInRange:aRange withString:aText];


    CGSize strSize = [newText sizeWithFont:textView.font constrainedToSize:CGSizeMake(200, 10000) lineBreakMode:UILineBreakModeWordWrap];

if (strSize.height > 100)

    {

        return NO; // can't enter more text
    }
    else
        return YES; // let the textView know that it should handle the inserted text
    }

到目前为止,一切都很好.当我尝试偷偷摸摸并在每次返回之前尽可能多地输入'x'时,问题就开始了.在这种情况下,我可以多得到4行...显然我不想允许.我认为这与lineBreakMode有关?有什么情况可以改变吗?我在文档中没有找到太多东西(但是再说一次,我通常很难理解它们).

So far so good. The problem starts when I try to be sneaky and enter as many 'x's as I can before each return. In that case, I can get an extra of 4 lines... which I obviously do not want to allow. I assume that this has something to do with the lineBreakMode? Is there any case to alter this? I haven't found much in the docs (but then again, I usually have a hard time understanding them).

我附上了两个屏幕截图以说明问题.如有任何建议,我将不胜感激.非常感谢!

I attached a couple of screenshots to illustrate the problem. I'd be grateful for any suggestions. Thanks a lot!

推荐答案

(希望我正确理解了您的问题...)

如果仔细观察,在 UITextView 中会有一个空白.如果您不小心使用 sizeWithFont:,在特殊情况下(因为您不尊重文本视图的边距),它可能会返回意外结果.

If you look closely, there's a margin in UITextView. If you use sizeWithFont: carelessly, it can return unexpected results in special cases (because you disrespect the text view's margin).

您应该1)调整在 sizeWithFont:中使用的宽度以尊重文本视图的边距,或者2)使用辅助的 UITextView 对象准确地计算内容大小

You should either 1) adjust the width you use in sizeWithFont: to respect the text view's margin or 2) use an auxiliary UITextView object to accurately compute the content size.

这篇关于iPhone:限制UITextView中的文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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