【问题标题】:Prevent user from entering more characters into uitextview防止用户在 uitextview 中输入更多字符
【发布时间】:2015-06-01 19:30:40
【问题描述】:

在 textview 达到给定高度后,如何防止用户在 uitextview 中输入更多字符?这是我认为可行但不可行的代码。我不能再添加任何字符,但由于某种原因我什至不能删除任何字符..

   - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {

        if (textView.frame.size.height > 102)
        {
            return NO;
        }
        return YES;
}

有什么想法吗? :(

【问题讨论】:

  • 您正在传递文本字段,那么您为什么要明确引用它(或另一个?)?
  • 哦,是的,谢谢。我编辑了帖子。

标签: ios7 xcode6 uitextview edit


【解决方案1】:

创建一个与编辑将产生的内容相匹配的新字符串。如果新字符串比现有字符串短,也返回YES

例子:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSMutableString *string = [NSMutableString stringWithString:[textView text]];
    [string replaceCharactersInRange:range withString:text];
    BOOL deleted = [string length] < [[textView text] length];
    if (deleted) {
        NSLog(@"Characters deleted");
        return YES;
    }
    if (textView.frame.size.height > 102)
    {
        return NO;
    }
    return YES;
}

【讨论】:

  • 我不确定我是否完全理解。你能在一些代码中显示它或更详细地解释它吗?
  • 更新了一个例子。
【解决方案2】:

这行得通吗?

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {

        NSLayoutManager* layoutManager = textView.layoutManager;
        NSTextContainer* textContainer = textView.textContainer;
        int glyphCount = layoutManager.numberOfGlyphs;
        if(text.length == 0) glyphCount--; //deleting

        CGRect textRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(0, glyphCount) inTextContainer: textContainer];

        if (textRect.size.height > 102)
        {
            return NO;
        }
        return YES;
}

【讨论】:

  • 不,不幸的是:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多