Reputation: 80
In termius, when you open the keyboard, there are extra keys on top of the keyboard as you can see in the picture.
How can I make this in swift?
Upvotes: 1
Views: 954
Reputation: 5410
Just add button to field:
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
keyboardToolbar.isTranslucent = false
keyboardToolbar.barTintColor = UIColor.white
let addButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(someFunction)
)
addButton.tintColor = UIColor.black
keyboardToolbar.items = [addButton]
textView.inputAccessoryView = keyboardToolbar
or another:
let button = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 60))
button.backgroundColor = UIColor.blue
button.setTitle("NEXT", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.addTarget(self, action: #selector(self. yourButton), for: .touchUpInside)
textField.inputAccessoryView = button
SwiftUI solution:
struct TestTextfield: UIViewRepresentable {
@Binding var text: String
var keyType: UIKeyboardType
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.keyboardType = keyType
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:)))
toolBar.items = [doneButton]
toolBar.setItems([doneButton], animated: true)
textfield.inputAccessoryView = toolBar
return textfield
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
}
extension UITextField{
@objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
self.resignFirstResponder()
}
}
Upvotes: 1
Reputation: 2057
You can use UIToolbar with any buttons you want, all you need to add that toolbar to the inputAccessoryView of the input textfield. like code below.
let bar = UIToolbar()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self,action:#selector(doneTapped))
bar.items = [doneButton]
bar.sizeToFit()
inputTextField.inputAccessoryView = bar
Upvotes: 0