how can i increase the height of an inputAccessoryView

前端 未结 2 1949
长发绾君心
长发绾君心 2021-01-31 11:25

I have spent several days on this with no solution in sight.

I have an inputAccessoryView which consists of a UIView containing a textV

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-31 11:50

    To make input accessory view grow vertically you just set its autoresizingMask = .flexibleHeight, calculate its intrinsicContentSize and let the framework do the rest.

    The code:

    class InputAccessoryView: UIView, UITextViewDelegate {
    
        let textView = UITextView()
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            // This is required to make the view grow vertically
            self.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
    
            // Setup textView as needed
            self.addSubview(self.textView)
            self.textView.translatesAutoresizingMaskIntoConstraints = false
            self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
            self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
    
            self.textView.delegate = self
    
            // Disabling textView scrolling prevents some undesired effects,
            // like incorrect contentOffset when adding new line,
            // and makes the textView behave similar to Apple's Messages app
            self.textView.isScrollEnabled = false
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override var intrinsicContentSize: CGSize {
            // Calculate intrinsicContentSize that will fit all the text
            let textSize = self.textView.sizeThatFits(CGSize(width: self.textView.bounds.width, height: CGFloat.greatestFiniteMagnitude))
            return CGSize(width: self.bounds.width, height: textSize.height)
        }
    
        // MARK: UITextViewDelegate
    
        func textViewDidChange(_ textView: UITextView) {
            // Re-calculate intrinsicContentSize when text changes
            self.invalidateIntrinsicContentSize()
        }
    
    }
    

提交回复
热议问题