Changing the frame of an inputAccessoryView in iOS 8

后端 未结 9 2125
遇见更好的自我
遇见更好的自我 2020-12-13 02:42

Long time lurker - first time poster!

I am having an issue while recreating a bar with a UITextView like WhatsApp does it.

I am using a custom <

9条回答
  •  一生所求
    2020-12-13 03:08

    To sum up JohnnyC's answer: set your inpitAccessoryView's autoresizingMask to .flexibleHeight, calculate its intrinsicContentSize and let the framework do the rest.

    Full code, updated for Swift 3:

    class InputAccessoryView: UIView, UITextViewDelegate {
    
        let textView = UITextView()
    
        override var intrinsicContentSize: CGSize {
            // Calculate intrinsicContentSize that will fit all the text
            let textSize = textView.sizeThatFits(CGSize(width: textView.bounds.width, height: CGFloat.greatestFiniteMagnitude))
            return CGSize(width: bounds.width, height: textSize.height)
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            // This is required to make the view grow vertically
            autoresizingMask = .flexibleHeight
    
            // Setup textView as needed
            addSubview(textView)
            textView.translatesAutoresizingMaskIntoConstraints = false
            addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textView]|", options: [], metrics: nil, views: ["textView": textView]))
            addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textView]|", options: [], metrics: nil, views: ["textView": textView]))
    
            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
            textView.isScrollEnabled = false
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        // MARK: UITextViewDelegate
    
        func textViewDidChange(_ textView: UITextView) {
            // Re-calculate intrinsicContentSize when text changes
            invalidateIntrinsicContentSize()
        }
    
    }
    

提交回复
热议问题