我正在实现自动增长 UITextView
.我的目标是 Whatsapp 中消息框的类似行为,当您的文本超过 1 行时,它会自动增长。
我正在使用下面描述的方法,它将高度约束存储在 UITextView
中。子类并在文本更改时对其进行修改。
当我在 TextView 中按下回车键时,我的解决方案动画正确,但当我的输入超出行尾时它不起作用。在这种情况下,它只是立即改变大小。
在代理的 - (void)textViewDidChange:(UITextView *)textView
上执行动画方法产生相同的结果。
如何使用自动布局系统正确设置 TextView 高度的动画?
我正在这样实现它:
@interface OEAutoGrowingTextView ()
@property (strong, nonatomic) NSLayoutConstraint *heightConstraint;
@end
@implementation OEAutoGrowingTextView
- (id)initWithFrame:(CGRect)frame
{
if ( !(self = [super initWithFrame:frame]) )
{
return nil;
}
[self commonInit];
return self;
}
- (void)awakeFromNib
{
[self commonInit];
}
- (void)commonInit
{
// If we are using auto layouts, than get a handler to the height constraint.
for (NSLayoutConstraint *constraint in self.constraints)
{
if (constraint.firstAttribute == NSLayoutAttributeHeight)
{
self.heightConstraint = constraint;
break;
}
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)textDidChange:(NSNotification *)notification
{
self.heightConstraint.constant = self.contentSize.height;
[UIView animateWithDuration:1.0f animations:^
{
[self layoutIfNeeded];
}];
}
@end
注意:执行以下操作无济于事。
- (void)textDidChange:(NSNotification *)notification
{
self.heightConstraint.constant = self.contentSize.height;
[UIView animateWithDuration:1.0f animations:^
{
[self layoutIfNeeded];
for (UIView *view in self.subviews)
{
[view layoutIfNeeded];
}
}];
}
进一步更新:这似乎是 iOS 7.x 中的一个错误,我认为它已在 iOS 8.0 上修复。
最佳答案
I tried wrapping the heightConstraint change in a UIView animation block and that didn't work
这不是您为约束更改设置动画的方式。您可以通过更改约束然后为布局本身设置动画来做到这一点,如下所示:
// change the text view constraint here
[UIView animateWithDuration:duration animations:^{
[self.textView layoutIfNeeded];
}];
关于ios - 使用自动布局动画 UITextView 调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701222/