How can I show done button on the decimal pad keyboard?

大城市里の小女人 提交于 2021-02-10 17:09:15

问题


I'm trying to learn Swift and I've done on the view screens. But as you can understand more easily by checking the screenshot, when I enter a value into a text field, there isn't any done button showing up so I can not hide the keyboard from the screen. And that makes it impossible to press the submit button which is located bottom of the screen view.

screenshoot while the keyboard is being shown

screenshoot while the keyboard is closed


回答1:


Firstly, create a new Swift File. Add this to the file :

import Foundation
import UIKit

extension UIViewController{
    func toolBar() -> UIToolbar{
        let toolBar = UIToolbar()
        toolBar.barStyle = .default
        toolBar.isTranslucent = true
        toolBar.barTintColor = UIColor.init(red: 0/255, green: 25/255, blue: 61/255, alpha: 1) //Write what you want for color
        let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        var buttonTitle = "Done" //Or "Tamam"
        var cancelButtonTitle = "Cancel" //Or "İptal" for Turkish
        let doneButton = UIBarButtonItem(title: buttonTitle, style: .done, target: self, action: #selector(onClickDoneButton))
        let cancelButton = UIBarButtonItem(title: cancelButtonTitle, style: .plain, target: self, action: #selector(onClickCancelButton))
        doneButton.tintColor = .white
        cancelButton.tintColor = .white
        toolBar.setItems([cancelButton, space, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        toolBar.sizeToFit()
        return toolBar
    }

    @objc func onClickDoneButton(){
        view.endEditing(true)
    }

    @objc func onClickCancelButton(){
        view.endEditing(true)
    }
}

And add this toolbar to your textfield :

yourTextField.inputAccessoryView = toolBar()

Hope it helps...




回答2:


You can add a toolbar as an input accessory :

     let toolBar = UIToolbar()
     toolBar.sizeToFit()
     let button = UIBarButtonItem(title: "Done", style: .plain, target: self, 
                                      action: #selector(dismiss))
     toolBar.setItems([button], animated: true)
     toolBar.isUserInteractionEnabled = true
     textField.inputAccessoryView = toolBar

Also you need to add dismiss method:

@objc func dismiss() {
   view.endEditing(true)
 }


来源:https://stackoverflow.com/questions/61332009/how-can-i-show-done-button-on-the-decimal-pad-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!