iOS: 自动增高的 textView

如 iPhone 内应用“信息”的输入框一样,输入文字过多或者输入换行,输入框可以随着内容自动变化。主要是计算内容的尺寸并相应更改输入框的frame。具体表现在:

  1. 更改输入框的 frame.origin.y;
  2. 更改输入框的高度。

两者的变化量是相同的。

为了能达到实时性,就要监听文字的变化,注册 UITextViewTextDidChangeNotification 的监听,并在合适的时候解除监听。

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChanged:) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)removeFromSuperview
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

在监听的方法中,更改 textView 的frame

- (void)textDidChanged:(NSNotification *)notif
{
    CGSize contentSize = self.textView.contentSize;
    if (contentSize.height > 140) {
        return;
    }
    CGFloat minus = 3;
    
    CGRect selfFrame = self.frame;
    CGFloat selfHeight = self.textView.superview.frame.origin.y * 2 + contentSize.height - minus + 2 * 2;
    CGFloat selfOriginY = selfFrame.origin.y - (selfHeight - selfFrame.size.height);
    selfFrame.origin.y = selfOriginY;
    selfFrame.size.height = selfHeight;
    self.frame = selfFrame;
}

在本例中,textView 是 self (UIView) 的 subView,并且设置好了 UIViewAutoresizingMask,所以更改 self.frame,变相地更改 textView.frame。

    aTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;

原文地址:https://www.cnblogs.com/ihojin/p/autoresizing-textview.html