I'm trying to implement an input accessory view that works just like Messages app in iOS. I've searched almost every SO questions regarding this topic, but couldn't find the solution that worked for me.
Here is the minimal reproducible code I created, referring to this SO post.
import UIKit
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
becomeFirstResponder() // seems unnecessary
}
override var inputAccessoryView: UIToolbar {
return self.keyboardAccessory
}
override var canBecomeFirstResponder: Bool {
return true
}
var textView: UITextView = {
let view = UITextView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .yellow
return view
}()
lazy var keyboardAccessory: UIToolbar = {
let inputAccessory = UIToolbar(frame: .init(x: 0, y: 0, width: 0, height: 100))
inputAccessory.addSubview(textView)
NSLayoutConstraint.activate([
textView.centerXAnchor.constraint(equalTo: inputAccessory.centerXAnchor),
textView.centerYAnchor.constraint(equalTo: inputAccessory.centerYAnchor),
textView.widthAnchor.constraint(equalToConstant: 200),
textView.heightAnchor.constraint(equalToConstant: 50)
])
inputAccessory.backgroundColor = .gray
return inputAccessory
}()
}
Every article I've seen suggests overriding inputAccessoryView
and canBecomeFirstResponder
, and that's it. However, the keyboard does not appear until I tap the textView
.
Can anyone let me know what I'm missing?
Edit
As @DonMag pointed out, Messages app in iOS does not show keyboard automatically. Please consider following UI in Facebook instead.
When I press the comment button, it pushes to another view controller while popping up the keyboard. The transition effect doesn't have to be exactly the same, but I want the keyboard become fully loaded within presented view controller, as if I called becomeFirstResponder()
in viewDidLoad
.