iOS

 

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

原文地址:https://www.cnblogs.com/junhuawang/p/7942807.html