ios - 如何使用 Swift 将 "Done"按钮添加到 iOS 中的小键盘?

标签 ios swift numpad

它在默认键盘上工作正常,但我无法在数字小键盘上工作。

有什么想法吗?

最佳答案

据我所知,您不能在键盘部分添加完成按钮;您需要将 inputAccessoryView 添加到 UITextFieldUITextView(如果您正在使用它)。

检查 documentation for more info .

编辑:勾选this question for an example关于如何做到这一点。

编辑 2:类似 example in Swift .

编辑 3:来自编辑 2 的代码,因为链接可能会过期。

override func viewDidLoad()
{
    super.viewDidLoad()

    //--- add UIToolBar on keyboard and Done button on UIToolBar ---//
    self.addDoneButtonOnKeyboard()
}

//--- *** ---//

func addDoneButtonOnKeyboard()
{
    var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50))
    doneToolbar.barStyle = UIBarStyle.BlackTranslucent

    var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction"))

    var items = NSMutableArray()
    items.addObject(flexSpace)
    items.addObject(done)

    doneToolbar.items = items
    doneToolbar.sizeToFit()

    self.textView.inputAccessoryView = doneToolbar
    self.textField.inputAccessoryView = doneToolbar

}

func doneButtonAction()
{
    self.textViewDescription.resignFirstResponder()
}

swift 4.2

func addDoneButtonOnKeyboard(){
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        doneToolbar.barStyle = .default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

        let items = [flexSpace, done]
        doneToolbar.items = items
        doneToolbar.sizeToFit()

        txtMobileNumber.inputAccessoryView = doneToolbar
    }

    @objc func doneButtonAction(){
        txtMobileNumber.resignFirstResponder()
    }

关于ios - 如何使用 Swift 将 "Done"按钮添加到 iOS 中的小键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28338981/

相关文章:

iphone - 我可以在 iPad 应用程序中获取 iPhone 数字键盘吗?

ios - 导航离开并返回后 ViewController 为空白

ios - 在 IOS 上向 NumberPad 添加下一步/完成按钮?

ios - iOS 11 和 iOS 10 页面显示不同

iPhone setDelegate 到之前分配的对象

ios - 如何在 iOS 上以编程方式在 Swift 4 中重启应用程序?

ios - 应用程序在后台运行时如何获取室内位置X和Y位置?

swift - 使用 Swift 3 在 Mac 上获取首选 wifi 网络列表

swift - .BackgroundColor 不改变背景颜色

android - 如何在为 Android 中的 EditText 按下删除/后退按钮时快速删除文本?