iOS-textView文本换行高度自动适应(3段代码)

简述:

由于开发中需要需要个类似QQ空间的一个评论功能,首先要做的输入框肯定是会换行的,因为iOS中(TextField)是单行组件,所以只能使用(TextView)这个多行组件了,可是在不做处理的情况下这个组件的文字在换行的时候会顶出输入框

解决思路:

1.通过Block 在TextView代理方法中把文字内容的ContentSize回调

//改变根据文字改变TextView的高度


typedef void (^ContentSizeBlock)(CGSize contentSize);

@interface ReplyInputView : UIView

@property (nonatomic,weak)UITextView *textfd;

-(void)setContentSizeBlock:(ContentSizeBlock) block;

@end


#pragma mark - textView delegate

-(void)textViewDidChange:(UITextView *)textView

{//根据字长度判断是否隐藏占位符Label

self.lblPlaceholder.hidden = (textView.text.length > 0);

CGSize contentSize = self.textfd.contentSize;

self.sizeBlock(contentSize);

}

2.在Vc中实例化我们输入框View的时候使用block调用更新约束的方法

#pragma mark - 初始化textview

-(void)initReplyInputView{

ReplyInputView *replyInputView =

[[ReplyInputView alloc]initWithFrame:

CGRectMake(0,KDeviceH-42-64, KDeviceW, 42) andAboveView:self.view];

replyInputView.textdelegate = self;

[self.view  addSubview:replyInputView];

self.replyInputView = replyInputView;

__weak typeof(self) weakSelf = self;

//使用block

[replyInputView setContentSizeBlock:^(CGSize contentSize) {

//更新约束

[weakSelf updateHeight:contentSize];

}];

}

//更新replyView的高度约束

-(void)updateHeight:(CGSize)contentSize

{

float height = contentSize.height +20;

CGRect frame = self.replyInputView.frame;

frame.origin.y -= height - frame.size.height;  //高度往上拉伸

frame.size.height = height;

self.replyInputView.frame = frame;

}

这样即可实现了

效果图:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容