textView高度随文字内容变化 聊天
1.
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define ChatHeight 45.0
<UITextViewDelegate> //设置代理
@property(strong, nonatomic) UIView * sendBackView;
@property(strong, nonatomic) UITextView * sendTextView;
2.//初始化ui
self.sendBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, WIDTH, ChatHeight)];
self.sendBackView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
[self.view addSubview:self.sendBackView];
// float heightView = self.sendBackView.frame.size.height;
self.sendTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 5, WIDTH - 10 - 90, 35)];
// self.sendTextView.backgroundColor = [UIColor lightGrayColor];
self.sendTextView.returnKeyType = UIReturnKeySend;
self.sendTextView.font = [UIFont systemFontOfSize:17];
self.sendTextView.editable = YES;
self.sendTextView.delegate = self;
[self.sendBackView addSubview:self.sendTextView];
3.delegate
// 这是一种很好的键盘下移方式
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"]) {
return NO;
}
return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
// 随机改变其高度
float textHeight = [self heightForString:textView.text fontSize:16 andWidth:textView.frame.size.width];
_sendTextViewHeight = textHeight;
self.sendTextView.frame = CGRectMake(10, 5, WIDTH - 10 - 90, _sendTextViewHeight);
self.sendBackView.frame = CGRectMake(0, HEIGHT - _sendBackViewHeight - _sendTextViewHeight - 10, WIDTH, _sendTextViewHeight + 10);
}
- (float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
UITextView *detailTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, width, 0)];
detailTextView.font = [UIFont systemFontOfSize:fontSize];
detailTextView.text = value;
CGSize deSize = [detailTextView sizeThatFits:CGSizeMake(width,CGFLOAT_MAX)];
return deSize.height;
}

浙公网安备 33010602011771号