UITextFieldWithDoneButton.swift 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. //
  2. // UITextFieldWithDoneButton.swift
  3. // Product Calculator
  4. //
  5. // Created by Suraj Kumar Mandal on 15/11/21.
  6. //
  7. import UIKit
  8. import Foundation
  9. class UITextFieldWithDoneButton: UITextField {
  10. required init?(coder aDecoder: NSCoder) {
  11. super.init(coder: aDecoder)
  12. self.addDoneButtonOnKeyboard()
  13. }
  14. fileprivate func addDoneButtonOnKeyboard() {
  15. let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
  16. doneToolbar.barStyle = .default
  17. let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
  18. let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
  19. let items = [flexSpace, done]
  20. doneToolbar.items = items
  21. doneToolbar.sizeToFit()
  22. self.inputAccessoryView = doneToolbar
  23. }
  24. @objc fileprivate func doneButtonAction() {
  25. self.resignFirstResponder()
  26. }
  27. }