天天看點

UITextView随輸入修改高度

這篇文章是為了解決在tableView上加textview,但是cell高度是随着輸入實時變化的,以及textview換行是上下抖動問題

話不多說,直接上代碼

if (@available(iOS 11.0, *)) {
        _mytable.estimatedRowHeight = 0;
        _mytable.estimatedSectionFooterHeight = 0;
        _mytable.estimatedSectionHeaderHeight = 0;
    }
           

[_mytable beginUpdates];[_mytable endUpdates];這兩個方法可以隻重新整理cell高度, reloaddata會時輸入失去焦點,不贊成使用

- (void)textViewDidChange:(UITextView *)textView {
    _dataArray[textView.tag-100] = textView.text;
    [textView sizeToFit];//使用sizeToFit方法處理textview随輸入大小變化以及自動換行問題
    _height=textView.frame.size.height; //_height記錄textview高度
    textView.frame = CGRectMake(0, 0, 300, textView.frame.size.height);
    
    [_mytable beginUpdates];
    [_mytable endUpdates];
}
           

将textview加在cell上,

UITextView * textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 300, 100) textContainer:nil];
    textView.backgroundColor = [UIColor greenColor];
    textView.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
    textView.textColor = [UIColor colorWithRed:74/255 green:74/255 blue:74/255 alpha:1];
    textView.tag=indexPath.row+100;
     textView.text=_dataArray[indexPath.row];
    [cell.contentView addSubview:textView];
    textView.delegate = self;
    // 以下兩行代碼是為了換行不抖動
    textView.layoutManager.allowsNonContiguousLayout=NO;
    textView.scrollEnabled = NO;
    [textView sizeToFit];//使用sizeToFit方法處理textview随輸入大小變化以及自動換行問題
    textView.frame = CGRectMake(0, 0, 300, textView.frame.size.height);
    _height=textView.frame.size.height; //_height記錄textview高度
           

我這個是隻有一個cell有輸入框,是以簡單處理了,如果有多行的,也可以加以區分處理。是不是很簡單啊