how to make UITextView height dynamic according to text length?

前端 未结 21 2212
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 05:44

As you can see in this image

the UITextView changes it\'s height according to the text length, I want to make it adjust it\'s height according to the te

相关标签:
21条回答
  • 2020-11-28 05:54

    Swift 4+

    This is extremely easy with autolayout! I'll explain the most simple use case. Let's say there is only a UITextView in your UITableViewCell.

    • Fit the textView to the contentView with constraints.
    • Disable scrolling for the textView.
    • Update the tableView in textViewDidChange.

    (You can do the last step in two ways - either pass the tableView instance to the cell or set the textView delegate to your view controller and implement the textViewDidChange delegate there and update the table view.)

    That's all!

    class TextViewCell: UITableViewCell {
    
        //MARK: UI Element(s)
        /// Reference of the parent table view so that it can be updated
        var tableView: UITableView!
    
        lazy var textView: UITextView = {
            let textView = UITextView()
            textView.isScrollEnabled = false
            // Other textView properties
            return textView
        }()
    
        //MARK: Padding Variable(s)
        let padding: CGFloat = 50
    
        //MARK: Initializer(s)
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
    
            addSubviews()
            addConstraints()
    
            textView.becomeFirstResponder()
        }
    
        //MARK: Helper Method(s)
        func addSubviews() {
            contentView.addSubview(textView)
        }
    
        func addConstraints() {
            textView.leadingAnchor  .constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
            textView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
            textView.topAnchor      .constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
            textView.bottomAnchor   .constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    extension TextViewCell: UITextViewDelegate {
    
        func textViewDidChange(_ textView: UITextView) {
            self.tableView.beginUpdates()
            self.tableView.endUpdates()
        }
    
    }
    

    Check out my repo for the full implementation.

    0 讨论(0)
  • 2020-11-28 05:59

    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:

    var frame = self.textView.frame
    frame.size.height = self.textView.contentSize.height
    self.textView.frame = frame
    
    0 讨论(0)
  • 2020-11-28 05:59

    just make a connection with your textView's height Constraint

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

    and use this code below

    textViewHeightConstraint.constant = self.textView.contentSize.height
    
    0 讨论(0)
  • 2020-11-28 06:00

    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;
      
      }
      
    0 讨论(0)
  • 2020-11-28 06:00

    I added these two lines of code and work fine for me.

    func adjustUITextViewHeight(textView : UITextView)
    {
         textView.translatesAutoresizingMaskIntoConstraints = true
         textView.scrollEnabled = false
         textView.sizeToFit()
    }
    
    0 讨论(0)
  • 2020-11-28 06:01

    Whenever you need to resize the textview according to the inside content size, like in messageing app. Use cocoapods(GrowingTextView), it will make your life easier, than coding the dynamic resizing of textview on your own.

    0 讨论(0)
提交回复
热议问题