[iOS] Xib realizes dynamic height of UITextView

[iOS] Xib realizes dynamic height of UITextView
final effect
Requirement:
  • Platform: iOS8.0+
  • Language: Swift3.1
  • Editor: Xcode8.3+
Realization:
  • Xib layout
[iOS] Xib realizes dynamic height of UITextView
InputView.xib
  • Kernel code

Principle: when the text input changes, the line number of the current input text is calculated, and the corresponding height view of the height is calculated accordingly. Then, the parent VC is called back to update the height constraint of the current view.

1. get the rect of the input text

Fileprivate var rectOfInputText: CGRect{let size = CGSize (width: textView.bounds.width - textView.textContainerInset.left - textView.textContainerInset.right, height: CGFloat.greatestFiniteMagnitude let Rect (textView.text) = as (NSString).BoundingRect with: size, options:.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font, context: nil! Return rect})

2. calculate the number of lines in the current input text based on the lineHeight font

Fileprivate, VaR, linesOfInputText:, Int{, return, Int (rectOfInputText.height / textView.font,.LineHeight)}

3. calculates the maximum height corresponding to the current view based on the input text

Fileprivate func (updateSelfHeightLayout) {let lines = linesOfInputText > maxiumLines maxiumLines linesOfInputText let?: height = CGFloat (lines) *textView.font!.lineHeight + textView.textContainerInset.bottom + textView.textContainerInset.top + layoutMargins.top + layoutMargins.bottom / callback callback (.NeedsUpdateLayoutOfHeight, height)}?

Calculate height when 4.UITextViewDelegate input changes

Extension InputView: UITextViewDelegate{func textViewDidChange (_ textView: UITextView) {updateSelfHeightLayout () / height calculation, callback update}}
usage
[iOS] Xib realizes dynamic height of UITextView
Storyboard settings
@IBOutlet weak var input: InputView @IBOutlet weak var inputHeightCons:! NSLayoutConstraint! Override func viewDidLoad (super.viewDidLoad) {(/ /) configuration method of input.configure (placeholder: "actionTitle: input comment", "reply" {[) unowned self] (type, info) in / if type to change the height of callback = =.NeedsUpdateLayoutOfHeight{self.inputHeightCons.constant = info as CGFloat UIView.animate (withDuration: 0.1! 0 options:, delay:,.CurveEaseInOut, animations: {self.view.layoutIfNeeded}), completion: (NIL)}}}
Be careful

This Demo, I mainly tell you how to dynamically calculate and update the height of the input box according to the input text content, without adding keyboard pop-up related event processing.

GitHub

Https://github.com/BackWorld/AutoHeightInputView

If you have help, don’t forget every point oh.