Add UIToolBar to all keyboards (swift)

后端 未结 5 1617
[愿得一人]
[愿得一人] 2021-01-31 05:19

I\'m trying to add a custom UIToolBar to all of my keyboards with as little repetition. The way I\'m currently doing it requires me to add the code to all my viewDidLoads and as

5条回答
  •  耶瑟儿~
    2021-01-31 05:40

    equivalent of vivian version in swift 3:

    extension UIViewController: UITextFieldDelegate {
        func addToolBar(textField: UITextField) {
            let toolBar = UIToolbar()
            toolBar.barStyle = .default
            toolBar.isTranslucent = true
            toolBar.tintColor = UIColor(red: 76 / 255, green: 217 / 255, blue: 100 / 255, alpha: 1)
            let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(donePressed))
            let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
            let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    
    
            toolBar.isUserInteractionEnabled = true
            toolBar.sizeToFit()
    
            textField.delegate = self
            textField.inputAccessoryView = toolBar
        }
    
        func donePressed() {
            view.endEditing(true)
        }
    
        func cancelPressed() {
            view.endEditing(true) // or do something
        }
    }
    

提交回复
热议问题