設置UITextView根據內容動態設置高度的簡單方法佈局
今天給你們介紹的是設置UITextView根據內容動態設置高度,我用的是SDLayout的佈局方式,方法很簡單能夠根據本身的佈局方式作修改,直接上代碼:
spa
- (void)textViewTextDidChangeNotiAction:(NSNotification *)obj{
UITextView *textView = (UITextView *)obj.object;
if(textView == self.contentTextView){
//得到textView的初始尺寸
CGFloat width = CGRectGetWidth(self.contentTextView.frame);
CGFloat height = CGRectGetHeight(self.contentTextView.frame);
//獲取當前內容下的textView的尺寸 CGSize newSize = [self.contentTextView sizeThatFits:CGSizeMake(width,MAXFLOAT)];
CGRect newFrame = self.contentTextView.frame;
// newFrame.size = CGSizeMake(fmax(width, newSize.width), fmax(height, newSize.height));
newFrame.size = CGSizeMake(newSize.width, newSize.height);
LYLog(@"新高度:%f",newFrame.size.height);
//self.contentTextView.frame = newFrame;
self.contentTextView.sd_resetLayout
.topSpaceToView(self, 10.f)
.leftSpaceToView(self, 15.f)
.rightSpaceToView(self, 15.f)
.heightIs(newFrame.size.height);
self.textNumLabel.sd_resetLayout
.topSpaceToView(self.contentTextView,5.f)
.rightSpaceToView(self, 15.f)
.widthIs(100.f)
.heightIs(20.f);
[self.contentTextView updateLayout];
self.inputText = self.contentTextView.text;
if([self.contentTextView.text isEqualToString:@"這一刻的想法"]){
self.inputText = @"";
}else {
if(self.contentTextView.text.length > 500){
[self.contentTextView endEditing:YES];
[MBProgressHUD showText:@"內容不能超過500個字" toView:nil];
self.inputText = [self.contentTextView.text substringToIndex:500];
self.contentTextView.text = self.inputText;
}
}
self.textNumLabel.text = [NSString stringWithFormat:@"%lu/%lu",(unsigned long)self.inputText.length,500 - self.inputText.length];
[self updateInputText];
LYLog(@"輸入的內容:%@",self.contentTextView.text);
}
[self setupAutoHeightWithBottomView:self.textNumLabel bottomMargin:10.f];
}
效果以下圖:code
圖一orm
圖二blog