iOS - UITextView放在自定義cell里面-自適應高度


 

textView放在自定義cell里面-自適應高度

1,textView有個屬性 scrollEnabled  要設置為NO;

2,設置tableview的時候  添加這兩行代碼:

    self.tableView.rowHeight = UITableViewAutomaticDimension;

    self.tableView.estimatedRowHeight = 100;

3,textView的底部要和contentView底部有個約束 xib

控件布局約束

復制代碼

- (void)awakeFromNib {

    [super awakeFromNib];

    self.textView.delegate = self;

    self.textView.scrollEnabled = NO ;

    self.oldTextViewBounds = self.textView.bounds;

}

復制代碼

要實現動態輸入文字讓cell隨時更改高度 要用tableView beginUpdates和endUpdates兩方法進行刷新,那么要什么時候進行刷新呢?要達到實時,所以我想到

textViewDidChange代理方法,這個會在文字改變的時候一直調用,所以在這個代理方法里面進行刷新是最合適不過的了,那么,我們又怎么能拿到tableView來進行調用更新呢?

其實我們可以用while循環查找cell的父控件來找到tableView  所以嘍,就是這樣:

復制代碼
- (void)textViewDidChange:(UITextView *)textView
{
    CGRect bounds = textView.bounds;
//     計算 text view 的高度
    CGSize maxSize = CGSizeMake(bounds.size.width, CGFLOAT_MAX);
    CGSize newSize = [textView sizeThatFits:maxSize];
    bounds.size = newSize;
    textView.bounds = bounds;
    // 讓 table view 重新計算高度

    //2.textView的高度不想等就更新 讓 table view 重新計算高度

    if (bounds.size.height != self.oldTextViewBounds.size.height) {

        UITableView *tableView = [self tableView];

        [tableView beginUpdates];

        [tableView endUpdates];

    }

    self.oldTextViewBounds = bounds;

}
- (UITableView *)tableView
{
    UIView *tableView = self.superview;
    while (![tableView isKindOfClass:[UITableView class]] && tableView) {
        tableView = tableView.superview;
    }
    return (UITableView *)tableView;
}
復制代碼

到此,完成自適應;

 

如果鍵盤彈出來會當着鍵盤  你可以用第三方的框架  IQKeyboardManager

 


免責聲明!

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



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