ios - 使用自动布局动画 UITextView 调整大小

标签 ios objective-c cocoa-touch autolayout

我正在实现自动增长 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/

相关文章:

ios - RealmSwift - librealm-ios.a 占用太多空间

ios - IOS7 升级后 Xcode 5 在 iPad 中编译的 iPhone 应用程序的框架问题(在 iPhone 中工作正常)

iphone - 当用户选择 UITextField 时,如何显示 UIDatePicker 而不是键盘?

iPhone 自定义相机覆盖(加图像处理): how-to

iPhone 在视频播放后强制方向

ios - 如何在 UIPageViewController 和子级之间正确传递对象

ios - 无法在标签与其边框之间添加空格

ios - 调整设备尺寸的 UILabel 字体大小

objective-c - NSToolbar 中的 NSComboBox 通过 IB 抛出异常

objective-c - 是否可以将 "Styled Maps"与 MKMapView 一起使用?