【问题标题】:Increase the height of UITextView according to its content [duplicate]根据其内容增加UITextView的高度[重复]
【发布时间】:2015-02-12 12:01:17
【问题描述】:

我的项目中有一个备注部分,我想在UITextView 中添加这些备注。我想要这样当我在文本视图中添加长文本时,整个文本视图会垂直增长以容纳文本。

我不希望 UITextView 滚动。相反,我希望它根据内容增加高度。

当我们有短文本时,我想要这样的:

当我向文本视图添加长文本时,它应该像这样增加它的高度:

如何实现它,这样高度会自动增加?

【问题讨论】:

    标签: ios objective-c uitextview


    【解决方案1】:

    你可以试试这样的:

    - (void)textViewDidChange:(UITextView *)textView
      {
        CGFloat fixedWidth = textView.frame.size.width;
        CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
        CGRect newFrame = textView.frame;
        newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
        textView.frame = newFrame;
        textview.scrollEnabled = NO;
      }
    

    【讨论】:

    【解决方案2】:

    您可以使用 NSAttributedString 获取文本的大小。

    NSAttributedString *string = [[NSAttributedString alloc] initWithString:textView.text attributes:@{NSFontAttributeName:textView.font}];
    float width = [string size].width;
    float height = [string size].height;
    // Then set the UITextView size using height and width
    

    您可以在委托方法中实现这一点:- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 并不断调整大小。

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多