项目要求
1、UITextView的高度随文字的增加而增加,类似微信
2、多于3行不再增加UITextView的高度
3、是亲测78高度三行,根据文字大小的不同亲们自行定义,灵活运用
查了很多网站都是在
- (BOOL)textView:(UITextView
*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString
*)text{
}
或
- (void)textViewDidChange:(UITextView *)textView{
}
中作处理,我试了一下,多多少少都有些问题,不是很完美,因此改变策略
使用通知:
[[NSNotificationCenter
defaultCenter]
addObserver:self
selector:@selector(textViewTextDidChange:)
name:UITextViewTextDidChangeNotification
object:self.textView];
总算问题少了很多,亲测目前使用还行,欢迎大家发现问题留言
源码:
@interface
TextViewHeightController ()<UITextViewDelegate>
@property(nonatomic,strong)
UITextView *textView;
//是否有滚动
@property (nonatomic,
assign,
getter=scrollFlag)
BOOL flag;
@end
- (void)viewDidLoad
{
[super
viewDidLoad];
self.navBar.titleLabel.text
= @"UITextView高度随文字自动增加";
//UITextView
self.textView
= [[UITextView
alloc]initWithFrame:CGRectMake(100,
64 +
150,
SCREEN_WIDTH -
200,
30)];
self.textView.font
= [UIFont
systemFontOfSize:17.0f];
self.textView.delegate
= self;
self.textView.layer.masksToBounds
= YES;
self.textView.layer.borderWidth
= 0.5;
self.textView.layer.borderColor
= [UIColor
lightGrayColor].CGColor;
//调整光标的位置,让光标出现在UITextView的正中间
self.textView.textContainerInset
= UIEdgeInsetsMake(5,0,
0,
0);
[self.view
addSubview:self.textView];
//改变文字的通知
[[NSNotificationCenter
defaultCenter]
addObserver:self
selector:@selector(textViewTextDidChange:)
name:UITextViewTextDidChangeNotification
object:self.textView];
// Do any additional setup after loading the view.
}
//通知
-(void)textViewTextDidChange:(NSNotification
*)notification{
//空格使用@"
"来代替
if([_textView.text
hasPrefix:@""]){
_textView.text=[_textView.text
stringByReplacingOccurrencesOfString:@"
"
withString:@""];
}
CGFloat height =
_textView.contentSize.height>78?78:_textView.contentSize.height+5;
[UIView
animateWithDuration:0.3
animations:^{
_textView.frame=CGRectMake(100,
CGRectGetMaxY(_textView.frame)-height,
_textView.frame.size.width,
height);
}];
return;
}
//可以滚动
- (void)scrollViewWillBeginDragging:(UIScrollView
*)scrollView{
_flag=YES;
}
//不可以滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView
*)scrollView{
_flag=NO;
}
- (void)scrollViewDidScroll:(UIScrollView
*)scrollView{
/**
*
判断是否拖动来设置frame
*/
if(!self.scrollFlag){
NSLog(@"%lf",_textView.contentSize.height);
if(_textView.contentSize.height>78){
[_textView
setContentOffset:CGPointMake(0,
_textView.contentSize.height-78
+ 5)];
}else{
[_textView
setContentOffset:CGPointMake(0,
0)];
}
}
}
OK !!!!!!!!!!!