TextView 高度计算,动态变化

1.原本使用下面方法计算,但是数据一直不太正确

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary *)attributes context:(nullable NSStringDrawingContext *)context

2.后来查询资料后使用KVO获取TextView的contentsize变化,得到TextView高度变化

[textView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UITextView *textView = (UITextView*)object;
    if([keyPath isEqualToString:@"contentSize"]) {
        textView.height = textView.contentSize.height
    }
}

你可能感兴趣的:(TextView 高度计算,动态变化)