Here is a solution for your problem how to create a custom UIToolBar and add to it custom elements like a UIButton etc:
#Swift 5
class ViewController: UIViewController, UITextFieldDelegate {
// will be added later to our custom ToolBar)
let dragButton = UIButton()
// the toolbar will appear above a keyboard of the UITextField
// it can be an outlet from a storyboard also
let someTextField = UITextField()
// here is our didLoad method)
override func viewDidLoad() {
super.viewDidLoad()
someTextField.delegate = self
//For exemple here we call our function what does all the toolbar setups
setupToolBar()
}
//setup toolbar
func setupToolBar(){
// to add a target for our drag button
// the target is below the setupToolBar function)
dragButton.addTarget(self, action:#selector(dragClicked), for: .touchDown)
dragButton.backgroundColor = .red
dragButton.frame = CGRect(x: 0, y: 0, width: 80, height: 4)
dragButton.contentMode = .scaleAspectFit
dragButton.setBackgroundImage(UIImage(named: "drag"), for: .normal)
// So here we do some stuff with the toolBar
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 100))
toolBar.barTintColor = .clear
toolBar.setBackgroundImage(UIImage(), forToolbarPosition: UIBarPosition.any, barMetrics: UIBarMetrics.default)
toolBar.setShadowImage(UIImage(), forToolbarPosition: UIBarPosition.any)
toolBar.backgroundColor = .white
toolBar.isOpaque = false
//The flexible space helps to arrange things inside the toolBar
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let ourButton = UIBarButtonItem.init(customView: dragButton)
// we added 2 flexible spaces to keep are button at the center of the toolBar
toolBar.setItems([flexibleSpace, hideButton, flexibleSpace], animated: true)
// and we add our toolBar with our UIButton above our someTextField keyboard)
someTextField.inputAccessoryView = toolBar
}
// Ok, here is our selector for dragButton in toolBar
@objc private func dragClicked(){
// here we can put some code what our button should perform
self.someTextField.endEditing(true)
}
}
Also you can create an extension of UITextField somewhere below a class and there create a custom toolbar