如何在小数点键盘上显示完成按钮?

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

我正在尝试学习 Swift 并且我已经在视图屏幕上完成了。但正如您通过查看屏幕截图可以更容易地理解的那样,当我在文本字段中输入一个值时,没有显示任何完成按钮,因此我无法从屏幕上隐藏键盘。这使得无法按下位于屏幕视图底部的提交按钮。

您可以添加工具栏作为输入附件:

     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

你还需要添加关闭方法:

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

首先,创建一个新的Swift 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)
    }
}

并将此 toolbar 添加到您的 textfield 中:

yourTextField.inputAccessoryView = toolBar()

希望对您有所帮助...

没有切换回 UIKit 使用了以下库

Link:https://github.com/siteline/SwiftUI-Introspect

import SwiftUI
import Introspect

struct ContentView : View {
@State var text = ""

var body: some View {
    TextField("placeHolder", text: $text)
       .keyboardType(.default)
       .introspectTextField { (textField) in
           let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textField.frame.size.width, height: 44))
           let flexButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
           let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textField.doneButtonTapped(button:)))
           doneButton.tintColor = .systemPink
           toolBar.items = [flexButton, doneButton]
           toolBar.setItems([flexButton, doneButton], animated: true)
           textField.inputAccessoryView = toolBar
        }
}

extension  UITextField {
   @objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
      self.resignFirstResponder()
   }
}