0

Found this code to insert the "Done" Button within the decimal keyboard pad and it works as long I don't use a custom view for the button like in this piece of code:

extension UITextField {
    func makeKeyboardToolBar(title: String) {
        let keyboardToolBar = UIToolbar()
        keyboardToolBar.sizeToFit()

        let flexibleSpace = UIBarButtonItem(barButtonSystemItem:
            UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)

        let bimage = UIImageView(image: UIImage(named: "icon_plus_50"))

        let doneButton = UIBarButtonItem(title: title, style: UIBarButtonItem.Style.done,  target: self, action: #selector(self.doneClicked))

        doneButton.customView = bimage

        keyboardToolBar.setItems([flexibleSpace, doneButton], animated: true)

        self.inputAccessoryView = keyboardToolBar
    }

    @objc func doneClicked() {
        self.endEditing(true)
    }
}

The image appears, but doesn't react. Do not set a custom view works instead, the "title" appears and doneClicked response as appropriate. There are similar questions but unfort. objective-c... Any help appreciate.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
frameworker
  • 298
  • 1
  • 3
  • 16

1 Answers1

1

Don't create or use the UIImageView. Just create the UIBarButtonItem with the image.

let doneButton = UIBarButtonItem(image: UIImage(named: "icon_plus_50"), style: .plain, target: self, action: #selector(doneClicked))

No need to set the customView.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Yes, it works and responds. But the image will be shown solid without the "image": It's just a blue circle with a white cross within (plus icon). The image that appears is the blue,solid circle wihtout the white cross? It's just a 50x50 png.... If I load it in a normal view, it will be shown okay. – frameworker Jul 07 '19 at 07:03
  • By default, toolbar images are meant to be templates. Only the alpha matters. If you want to show the image as-is, then you need to change `UIImage(named: "icon_plus_50")` to `UIImage(named: "icon_plus_50").withRenderingMode(.alwaysOriginal)`. – rmaddy Jul 07 '19 at 07:10
  • Where is your frame for this object? I believe if you set a frame for a custom UIBarButtonItem it will not appear as UIBarButtonItem needs auto-layout constraints. this could be the solution if you are setting the frames' height and width instead of using auto-layout – David Henry Jul 07 '19 at 07:10
  • @DavidLintin Given my answer, no frame needs to be set. Perhaps you meant to post your comment on the question instead of this answer. – rmaddy Jul 07 '19 at 07:11
  • @frameworker Glad to help. Please don't forget to indicate that your question has been resolved by clicking the checkmark to the left of the answer. You may wish to do this with your earlier questions as well. – rmaddy Jul 07 '19 at 07:26