1.
添加内容变化的通知响应事件:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name: UITextViewTextDidChangeNotification object:nil];
2 实现方法
- (void)textChanged:(NSNotification *)notification{
if (self.textView.contentSize.height>45) {
CGFloat textViewHeight=self.textView.contentSize.height;
NSDictionary *dict =[[NSDictionary alloc]
initWithObjectsAndKeys:@(textViewHeight+ViewHeight),@"textOne",nil];
[[NSNotificationCenter defaultCenter]postNotificationName:NotificationAttitudeHeight object:nil userInfo:dict];
}else{
// CGFloat textViewHeight=self.textView.contentSize.height;
NSDictionary *dict =[[NSDictionary alloc]
initWithObjectsAndKeys:@(50),@"textOne",nil];
[[NSNotificationCenter defaultCenter]postNotificationName:NotificationAttitudeHeight object:nil userInfo:dict];
}
}
还有一个地方需要注意,当你清空输入框时(_textView.text=@"";),不会自动触发textChanged:,你需要重写setText:方法来调用textChanged:。并且你清空textview后,你拿到的contentsize也不准确,所以还需要根据text是否为空来设定一个最小的高度。
调用setneedslayout