iOS 設置TextView 只能輸入兩行

http://www.itstrike.cn/Question/c51c60a2-4ea9-4902-8ef9-0f14d1fcba9b.htmlhtml

 

- (void)viewDidLoad {htm

    [super viewDidLoad];ci

    // Do any additional setup after loading the view, typically from a nib.string

    

    UITextView * view = [[UITextView alloc]init];it

    

    view.frame = CGRectMake(20, 30, [UIScreen mainScreen].bounds.size.width-40, [UIScreen mainScreen].bounds.size.height-30);io

    

    view.font= [UIFont systemFontOfSize:15];im

    

    view.delegate =  self;call

    

    [self.view addSubview:view];di

    

    view.textContainer.maximumNumberOfLines = 2;view

    

    

}

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

{

    NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];

    

    NSDictionary *textAttributes = @{NSFontAttributeName : textView.font};

    

    CGFloat textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset));

    textWidth -= 2.0f * textView.textContainer.lineFragmentPadding;

    CGRect boundingRect = [newText boundingRectWithSize:CGSizeMake(textWidth, 0)

                                                options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading

                                             attributes:textAttributes

                                                context:nil];

    

    NSUInteger numberOfLines = CGRectGetHeight(boundingRect) / textView.font.lineHeight;

    

    return newText.length <= 500 && numberOfLines <= 2;

}

相關文章
相關標籤/搜索