iOS评论框高度的自动增减核心代码

#import "ChatTooBar.h"
#import "ZXTextView.h"

@interface ChatTooBar ()

@property (nonatomic, strong) ZXTextView *textView;

@end

@implementation ChatTooBar

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUpView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpView]; 
    }
    return self;
}

- (void)setUpView{
    
    self.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:245 / 255.0 blue:245 / 255.0 alpha:1.0];
    
    _textView = [[ZXTextView alloc] init];
    _textView.font = [UIFont systemFontOfSize:16];
    _textView.layer.borderWidth = 1 / [UIScreen mainScreen].scale;
    _textView.layer.borderColor = [UIColor colorWithRed:188 / 255.0 green:188 / 255.0 blue:188 / 255.0 alpha:1.0].CGColor;
    [self addSubview:_textView];
    
    [self addObserver];
}

- (void)addObserver{
    [_textView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGFloat contentH = [self getTextViewContentH:_textView];
        CGFloat textViewH = _textView.bounds.size.height;
        if (!_textView.text.length || (contentH == textViewH)) {
            return;
        } else {
            [UIView animateWithDuration:0.25 animations:^{
                _textView.frame = CGRectMake(_textView.frame.origin.x, _textView.frame.origin.y, _textView.bounds.size.width, contentH);
                self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width,contentH + 10);
            }];
        }
    }
}

#pragma mark - private

- (CGFloat)getTextViewContentH:(UITextView *)textView{
    return ceilf([textView sizeThatFits:textView.frame.size].height);
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    _textView.frame = CGRectMake(20, 5, self.bounds.size.width - 40, self.bounds.size.height - 10);
}

- (void)dealloc{
    [self removeObserver:self forKeyPath:@"contentSize"];
}


@end

你可能感兴趣的:(iOS评论框高度的自动增减核心代码)