我在设置 UITextView
的高度时遇到问题,例如消息应用程序。这是通过在换行符出现时增加它的高度来实现的。
我的问题是,当用户编辑文本内容时,它并没有降低 Container 的高度,其中 textview
是一个 child 。
我正在使用自动布局和这段代码
- (void)textViewDidChange:(UITextView *)textView {
UITextPosition* pos = self.posttextView.endOfDocument;//explore others like beginningOfDocument if you want to customize the behaviour
CGRect currentRect = [self.posttextView caretRectForPosition:pos];
if (currentRect.origin.y > previousRect.origin.y){
if (self.containerHeightt.constant == 99) {
return;
}
self.containerHeightt.constant += 10;
NSLog(@"the container height is %f",self.containerHeightt.constant);
}
previousRect = currentRect;
}
请告诉我如何检测何时从 textview
中删除一行,然后降低容器的高度。
最佳答案
请走下面的路-
确保您的 UITextView 滚动已禁用。
添加一个具有默认高度的虚拟 UITextView 高度约束,将其连接到
IBOutlet (NSLayoutConstraint - textViewHeightConstraint).
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewHeightConstraint;
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
CGFloat myMaxSize = 480.0f;
CGRect frameRect = textView.frame;
CGRect rect = [textView.text
boundingRectWithSize:CGSizeMake(frameRect.size.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: textView.font}
context:nil];
CGSize size = rect.size;
if (size.height > myMaxSize) {
size.height = myMaxSize;
[textView setScrollEnabled:YES];
}
frameRect.size = size;
self.textViewHeightConstraint.constant = size.height;
}
关于ios - 像消息app一样动态设置uitextview的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641079/