限制UITextView中的文本

Sea*_*ean 5 cocoa-touch

我试图将文本输入限制为可可触摸中的UITextView.我真的想限制行数而不是字符数.到目前为止,我有这个来计算行数:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"]) {
        rows++;
    }
    NSLog(@"Rows: %i", rows);
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果自动换行而不是用户按下返回键,则不起作用.有没有办法检查文本是否包装类似于检查"\n"?

谢谢.

Jan*_*les 14

不幸的是,使用NSString -stringWithFont:forWidth:lineBreakMode:不起作用 - 你选择的包装模式,文本包装的宽度小于当前宽度,并且高度在任何溢出行上变为0.为了得到一个真实的数字,将字符串放入一个比你需要的更高的框架 - 然后你将得到一个高于你的实际高度的高度.

注意我的软糖(从宽度减去15).这可能与我的观点有关(我有一个在另一个内),所以你可能不需要它.

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText
{
        NSString* newText = [aTextView.text stringByReplacingCharactersInRange:aRange withString:aText];

        // TODO - find out why the size of the string is smaller than the actual width, so that you get extra, wrapped characters unless you take something off
        CGSize tallerSize = CGSizeMake(aTextView.frame.size.width-15,aTextView.frame.size.height*2); // pretend there's more vertical space to get that extra line to check on
        CGSize newSize = [newText sizeWithFont:aTextView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];

        if (newSize.height > aTextView.frame.size.height)
            {
            [myAppDelegate beep];
            return NO;
            }
        else
            return YES;
}
Run Code Online (Sandbox Code Playgroud)