我正在實施自動增長UITextView
。我打算在Whatsapp中使用類似的消息框行爲,當文本超過1行時自動填充。Animate UITextView使用自動佈局調整大小
我正在使用下面描述的方法,將高度約束存儲在UITextView
子類中,並在文本更改時對其進行修改。
當我按下輸入鍵時,我的解決方案可以正確動畫,但在輸入行結束時它不起作用。在這種情況下,它只是立即改變大小。
對代表執行動畫的- (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。
是的,但是如何在UITextView的autoLayout方法中自動發生約束更改時觸發動畫? –
它不會自動發生。如果你的文本視圖正在改變大小,那是因爲你正在改變它的大小。所以如果你可以直接改變它的約束,你可以用動畫改變它的約束。 – matt
在'layoutSubviews'裏面設置'layoutIfNeeded'的動畫看起來不太好。並且它也不能按預期工作。我想問的是,在'UITextView'的'layoutSubviews'中發生heightConstraint變化的情況下,我應該在哪裏爲'layoutIfNeeded'設置動畫? –