iOS -- 不可編輯的UITextView 自動調整高度


     _textView  = [[UITextView alloc] initWithFrame:CGRectMake(13, 10, UIScreenWidth-26, 20)];
        [self.contentView addSubview:_textView];
        _textView.textColor = UIColorFromRGB(0x111111);
        _textView.font = [UIFont systemFontOfSize:16];
        _textView.editable = NO;
        _textView.backgroundColor = [UIColor yellowColor];
        //_textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//相對於父視圖不會改變屬性
        _textView.textContainer.lineFragmentPadding = 0;
        _textView.textContainerInset = UIEdgeInsetsZero;
      [self textViewDidChange:_textView];


//不可編輯的UITextView 自動調整高度
- (void)textViewDidChange:(UITextView *)textView{
    CGRect frame = textView.frame;
    NSDictionary *attri = @{NSFontAttributeName:textView.font};
    CGSize size = [textView.text boundingRectWithSize:CGSizeMake(280, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
    
    frame.size.height = size.height > 1 ? size.height : 64;
    textView.frame = frame;
    
    //文本居中
    CGRect textFrame = [[textView layoutManager] usedRectForTextContainer:[textView textContainer]];
    CGFloat offsetY = (textView.frame.size.height - textFrame.size.height)/2;
    textView.textContainerInset = UIEdgeInsetsMake(offsetY, 0, 0, 0);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM