阻止用户在uitextview中输入更多字符

时间:2015-06-01 19:30:41

标签: ios7 xcode6 uitextview edit

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

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

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

有什么想法吗? :(

2 个答案:

答案 0 :(得分:0)

创建一个与编辑产生的匹配的新字符串。如果新字符串比现有字符串短,则还返回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;
}

答案 1 :(得分:0)

这有用吗?

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