ios 如何根据文本长度使 UITextView 高度动态化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38714272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:49:01  来源:igfitidea点击:

how to make UITextView height dynamic according to text length?

iosswiftuitextview

提问by DeyaEldeen

As you can see in this image

正如你在这张图片中看到的

the UITextViewchanges it's height according to the text length, I want to make it adjust it's height according to the text length.

UITextView根据文本长度它的高度的变化,我想让它根据文本长度调节它的高度。

*I saw other questions, but solutions there didn't work for me

*我看到了其他问题,但那里的解决方案对我不起作用

example

例子

回答by DeyaEldeen

this Worksfor me, all other solutions didn't.

这个作品对我来说,所有其他解决方案都没有。

func adjustUITextViewHeight(arg : UITextView)
{
    arg.translatesAutoresizingMaskIntoConstraints = true
    arg.sizeToFit()
    arg.scrollEnabled = false
}

In Swift 4 the syntax of arg.scrollEnabled = falsehas changed to arg.isScrollEnabled = false.

在 Swift 4 中, 的语法arg.scrollEnabled = false已更改为arg.isScrollEnabled = false.

回答by Tum

In Storyboard / Interface Builder simply disable scrolling in the Attribute inspector.

在 Storyboard / Interface Builder 中,只需在属性检查器中禁用滚动。

In code textField.scrollEnabled = falseshould do the trick.

在代码中textField.scrollEnabled = false应该可以解决问题。

回答by Samuel Noyes

Give this a try:

试试这个:

CGRect frame = self.textView.frame;
frame.size.height = self.textView.contentSize.height;
self.textView.frame = frame;

Edit- Here's the Swift:

编辑 - 这是 Swift:

var frame = self.textView.frame
frame.size.height = self.textView.contentSize.height
self.textView.frame = frame

回答by ZAFAR007

Swift 4

斯威夫特 4

Add It To Your Class

将其添加到您的班级

UITextViewDelegate

UITextViewDelegate

func textViewDidChange(_ textView: UITextView) {
      let fixedWidth = textView.frame.size.width
      textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
      let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
      var newFrame = textView.frame
      newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
      textView.frame = newFrame
}

回答by Akash Kundu

Tested on Xcode 11.2.1, Swift 5.1:

在 Xcode 11.2.1、Swift 5.1 上测试:

All I had to do was:

我所要做的就是:

  1. Set the constraints to the top, left, and rightof the textView.
  2. Disable scrollingin Storyboard.
  1. 将约束设置为 textView 的顶部、左侧和右侧
  2. 在 Storyboard 中禁用滚动

Doing so allowed autolayout to kick in and dynamically size the textView based on its content.

这样做允许自动布局启动并根据其内容动态调整 textView 的大小。

回答by Brady Huang

Followed by DeyaEldeen's answer.
In my case. I grow the textview height automatically by adding

接着是DeyaEldeen的回答。
就我而言。我通过添加自动增加 textview 高度

swift 3

迅捷 3

textView.translatesAutoresizingMaskIntoConstraints = false textView.isScrollEnabled = false

textView.translatesAutoresizingMaskIntoConstraints = false textView.isScrollEnabled = false

回答by superfandick

If your textViewis allowed to grow as tall as the content, then

如果textView允许您的内容与内容一样高,那么

textView.isScrollEnabled = false

should just work with autolayout.

应该只使用自动布局。

If you want to remain the textViewto be scrollable, you need to add an optional height constraint,

如果你想保持textView可滚动,你需要添加一个可选的高度约束,

internal lazy var textViewHeightConstraint: NSLayoutConstraint = {
  let constraint = self.textView.heightAnchor.constraint(equalToConstant: 0)
  constraint.priority = .defaultHigh
  return constraint
}()

public override func layoutSubviews() {
  super.layoutSubviews()

  // Assuming there is width constraint setup on the textView.
  let targetSize = CGSize(width: textView.frame.width, height: CGFloat(MAXFLOAT))
  textViewHeightConstraint.constant = textView.sizeThatFits(targetSize).height
}

The reason to override layoutSubviews()is to make sure the textView is laid out properly horizontally so we can rely on the width to calculate the height.

覆盖的原因layoutSubviews()是确保 textView 正确水平布局,以便我们可以依靠宽度来计算高度。

Since the height constraint is set to a lower priority, if it runs out space vertically the actual height of the textViewwill be less than the contentSize. And the textView will be scrollable.

由于高度约束设置为较低的优先级,如果它在垂直方向上耗尽空间,则 的实际高度textView将小于contentSize. 并且 textView 将是可滚动的。

回答by Rishabh Shukla

just make a connection with your textView's height Constraint

只需与您的 textView 的高度约束建立联系

@IBOutlet var textView: UITextView!
@IBOutlet var textViewHeightConstraint: NSLayoutConstraint!

and use this code below

并在下面使用此代码

textViewHeightConstraint.constant = self.textView.contentSize.height

回答by oscar castellon

SWIFT 4

快速 4

Change the size when typing

键入时更改大小

UITextViewDelegate

UITextViewDelegate

func textViewDidChange(_ textView: UITextView) {
        yourTextView.translatesAutoresizingMaskIntoConstraints = true
        yourTextView.sizeToFit()
        yourTextView.isScrollEnabled = false

        let calHeight = yourTextView.frame.size.height
        yourTextView.frame = CGRect(x: 16, y: 193, width: self.view.frame.size.width - 32, height: calHeight)
    }

Change the size when load

加载时更改大小

func textViewNotasChange(arg : UITextView) {
        arg.translatesAutoresizingMaskIntoConstraints = true
        arg.sizeToFit()
        arg.isScrollEnabled = false

        let calHeight = arg.frame.size.height
        arg.frame = CGRect(x: 16, y: 40, width: self.view.frame.size.width - 32, height: calHeight)
    }

Call the function of the second option like this:

像这样调用第二个选项的函数:

textViewNotasChange(arg: yourTextView)

回答by Shaik Riyaz

it's straight forward to do in programatic way. just follow these steps

以编程方式进行操作很简单。只需按照这些步骤

  1. add an observer to content length of textfield

    [yourTextViewObject addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
    
  2. implement observer

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UITextView *tv = object;
    
        //Center vertical alignment
        CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
        topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
        tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
    
    
        mTextViewHeightConstraint.constant = tv.contentSize.height;
    
        [UIView animateWithDuration:0.2 animations:^{
    
            [self.view layoutIfNeeded];
        }];
    
    }
    
  3. if you want to stop textviewHeight to increase after some time during typing then implement this and set textview delegate to self.

    -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
        if(range.length + range.location > textView.text.length)
        {
            return NO;
        }
    
        NSUInteger newLength = [textView.text length] + [text length] - range.length;
    
        return (newLength > 100) ? NO : YES;
    
    }
    
  1. 将观察者添加到文本字段的内容长度

    [yourTextViewObject addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
    
  2. 实施观察者

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UITextView *tv = object;
    
        //Center vertical alignment
        CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
        topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
        tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
    
    
        mTextViewHeightConstraint.constant = tv.contentSize.height;
    
        [UIView animateWithDuration:0.2 animations:^{
    
            [self.view layoutIfNeeded];
        }];
    
    }
    
  3. 如果你想在打字过程中一段时间​​后停止 textviewHeight 增加然后实现这一点并将 textview 委托设置为 self.

    -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
        if(range.length + range.location > textView.text.length)
        {
            return NO;
        }
    
        NSUInteger newLength = [textView.text length] + [text length] - range.length;
    
        return (newLength > 100) ? NO : YES;
    
    }