【问题标题】:How to add "Done" button to Numpad in iOS using Swift?如何使用 Swift 在 iOS 中的 Numpad 中添加“完成”按钮?
【发布时间】:2015-04-05 00:20:11
【问题描述】:

使用默认键盘可以正常工作,但我无法使用小键盘。

有什么想法吗?

【问题讨论】:

标签: ios swift numpad


【解决方案1】:

据我所知,您不能在键盘部分添加完成按钮;您必须在UITextFieldUITextView 中添加inputAccessoryView(如果您正在使用)。

检查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()
}

斯威夫特 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()
    }

【讨论】:

  • 完美运行。快速简便的实施。谢谢!
  • 你可以改成这个,你不必本地化按钮:让完成:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneButtonAction))
【解决方案2】:

首先让我告诉你一件事,你可以在你的默认键盘上添加一个完成按钮。实际上,今天我刚刚解决了这个问题并解决了。现成的代码,只需将其放在您的 .swift 类中。我正在使用 Xcode 7 并使用 iPad Retina(ios 9) 进行测试。

反正这里不谈代码了。

  //Creating an outlet for the textfield
  @IBOutlet weak var outletTextFieldTime: UITextField!

  //Adding the protocol of UITextFieldDelegate      
  class ReservationClass: UIViewController, UITextFieldDelegate { 

  func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
  //Making A toolbar        
  let keyboardDoneButtonShow = UIToolbar(frame: CGRectMake(0, 0,  self.view.frame.size.width, self.view.frame.size.height/17))
  //Setting the style for the toolbar
    keyboardDoneButtonShow.barStyle = UIBarStyle .BlackTranslucent        
  //Making the done button and calling the textFieldShouldReturn native method for hidding the keyboard.
  let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("textFieldShouldReturn:"))
  //Calculating the flexible Space.
    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
  //Setting the color of the button.
    item.tintColor = UIColor .yellowColor()
  //Making an object using the button and space for the toolbar        
  let toolbarButton = [flexSpace,doneButton]
  //Adding the object for toolbar to the toolbar itself
  keyboardDoneButtonShow.setItems(toolbarButton, animated: false)
  //Now adding the complete thing against the desired textfield
    outletTextFieldTime.inputAccessoryView = keyboardDoneButtonShow
    return true

}

//Function for hidding the keyboard.
func textFieldShouldReturn(textField: UITextField) -> Bool {
    self.view.endEditing(true)
    return false
   }
}

这给了我解决方案...

我只想告诉你一件事,这是我在最近的项目中使用的有效解决方案。我发布了这个,因为这个问题没有可用的解决方案。承诺的工作代码和解释。

编辑:-

使其更专业...如果您遵循上述代码,那么它也会为您提供有效的解决方案,但在这里我试图使其更专业。请注意代码MOD。我用引号留下了之前未使用的代码。

变化..

  1. 创建单个按钮对象
  2. 将其设置为工具栏
  3. 减小先前创建的工具栏的大小
  4. 使用 FlexSpace 和 NegativeSpace 将自定义按钮定位到屏幕左侧。

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    let keyboardDoneButtonShow = UIToolbar(frame: CGRectMake(200,200, self.view.frame.size.width,30))
    
    // self.view.frame.size.height/17
    keyboardDoneButtonShow.barStyle = UIBarStyle .BlackTranslucent
    let button: UIButton = UIButton()
    button.frame = CGRectMake(0, 0, 65, 20)
    button.setTitle("Done", forState: UIControlState .Normal)
    button.addTarget(self, action: Selector("textFieldShouldReturn:"), forControlEvents: UIControlEvents .TouchUpInside)
    button.backgroundColor = UIColor .clearColor()
    // let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("textFieldShouldReturn:"))
    let doneButton: UIBarButtonItem = UIBarButtonItem()
    doneButton.customView = button
    let negativeSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
    negativeSpace.width = -10.0
    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    //doneButton.tintColor = UIColor .yellowColor()
    let toolbarButton = [flexSpace,doneButton,negativeSpace]
    keyboardDoneButtonShow.setItems(toolbarButton, animated: false)
    outletTextFieldTime.inputAccessoryView = keyboardDoneButtonShow
    return true
    }
    

它现在给了我以下...此外尝试匹配图片并找到更改。

谢谢。

希望这会有所帮助。抱歉回答太长了。

【讨论】:

    【解决方案3】:

    您可以将带有完成按钮的工具栏添加到键盘。 InputAccessoryView 文本字段的属性可用于设置此工具栏。

    以下是我在案例中使用的代码

    //Add done button to numeric pad keyboard
     let toolbarDone = UIToolbar.init()
     toolbarDone.sizeToFit()
     let barBtnDone = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Done,
             target: self, action: #selector(VerifyCardViewController.doneButton_Clicked(_:)))
    
     toolbarDone.items = [barBtnDone] // You can even add cancel button too
     txtCardDetails3.inputAccessoryView = toolbarDone
    

    【讨论】:

      【解决方案4】:

      如果您的Done 按钮应该只是关闭数字键盘,那么最简单的版本是调用resignFirstResponder 作为选择器,如下所示:

      UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: textField, action: #selector(UITextField.resignFirstResponder))
      

      此代码适用于 iOS9 和 Swift 2,我在我的应用程序中使用它:

      func addDoneButtonOnNumpad(textField: UITextField) {
      
        let keypadToolbar: UIToolbar = UIToolbar()
      
        // add a done button to the numberpad
        keypadToolbar.items=[
          UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: textField, action: #selector(UITextField.resignFirstResponder)),
          UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
        ]
        keypadToolbar.sizeToFit()
        // add a toolbar with a done button above the number pad
        textField.inputAccessoryView = keypadToolbar
      }
      

      【讨论】:

        【解决方案5】:

        Swift-3 版本Marko 的解决方案 - 对我有用

        在我的例子中,我有一个 UITextField 标识为textfield

        func addDoneButtonOnKeyboard() {
            let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
            doneToolbar.barStyle       = UIBarStyle.default        
            let flexSpace              = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            let done: UIBarButtonItem  = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(ViewController.doneButtonAction))
        
            var items = [UIBarButtonItem]()
            items.append(flexSpace)
            items.append(done)
        
            doneToolbar.items = items
            doneToolbar.sizeToFit()
        
            self.textfield.inputAccessoryView = doneToolbar
        }
        
        func doneButtonAction() {
            self.textfield.resignFirstResponder()
        }
        

        【讨论】:

          【解决方案6】:

          根据 Marko Nikolovski 的回答

          这是 Objective-C 的答案:

          - (void)ViewDidLoad {
          [self addDoneButtonOnKeyboard];
          }
          
          - (void)addDoneButtonOnKeyboard {
          UIToolbar *toolBarbutton = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
          toolBarbutton.barStyle = UIBarStyleBlackTranslucent;
          
          UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
          UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonAction)];
          
          NSMutableArray *items = [[NSMutableArray alloc] init];
          [items addObject:barBtnItem];
          [items addObject:done];
          
          toolBarbutton.items = items;
          [toolBarbutton sizeToFit];
          
          self.timeoutTextField.inputAccessoryView = toolBarbutton;
          }
          
          - (void)doneButtonAction {
          [self.view endEditing:YES];
          }
          

          【讨论】:

            【解决方案7】:

            Swift 5 解决方案使用@IBInpectable 和扩展。对于项目中的每个 UITextField,Interface Builder 中的 Attribute Inspector 下都会出现一个下拉列表。

            extension UITextField{    
                @IBInspectable var doneAccessory: Bool{
                    get{
                        return self.doneAccessory
                    }
                    set (hasDone) {
                        if hasDone{
                            addDoneButtonOnKeyboard()
                        }
                    }
                }
            
                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()
            
                    self.inputAccessoryView = doneToolbar
                }
            
                @objc func doneButtonAction()
                {
                    self.resignFirstResponder()
                }
            }
            

            【讨论】:

            • 很棒的答案。我希望每个人都在这里向下滚动。
            • 正是我想要的。谢谢
            【解决方案8】:

            您可以创建自定义类。我正在使用 Swift 4

            class UITextFieldWithDoneButton: UITextField {
                required init?(coder aDecoder: NSCoder) {
                    super.init(coder: aDecoder)
                    self.addDoneButtonOnKeyboard()
                }
            
                fileprivate 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()
            
                    self.inputAccessoryView = doneToolbar
                }
            
                @objc fileprivate func doneButtonAction() {
                    self.resignFirstResponder()
                }
            }
            

            【讨论】:

            • 这对我来说是一种享受。只需复制并粘贴到 .swift 文件的底部,然后使用:textfieldOutput.addDoneButtonOnKeyboard() 到 ViewDidLoad 中。谢谢!
            【解决方案9】:

            我能找到的最简单的解决方案 - 适用于 Swift 4.2 - 希望这会有所帮助 :)

            extension UITextField {
            
               func addDoneButtonOnKeyboard() {
                   let keyboardToolbar = UIToolbar()
                   keyboardToolbar.sizeToFit()
                   let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                       target: nil, action: nil)
                   let doneButton = UIBarButtonItem(barButtonSystemItem: .done,
                       target: self, action: #selector(resignFirstResponder))
                   keyboardToolbar.items = [flexibleSpace, doneButton]
                   self.inputAccessoryView = keyboardToolbar
               }
            }
            

            然后您可以在 textFieldDidEndEditing 委托方法中处理完成的操作,或者只需将自定义方法添加到扩展并将其设置在 doneButton 的选择器中。

            【讨论】:

            • 优秀、简单、优雅的解决方案!
            【解决方案10】:

            在任何键盘上添加“完成”按钮的简单方法是添加通用库

            IQKeyboardManager

            在应用程序的appdelegate中添加以下代码(_应用程序:UIApplication,didFinishLaunchingWithOptions。

            IQKeyboardManager.shared.enable = true
            IQKeyboardManager.shared.enableAutoToolbar = true
            IQKeyboardManager.shared.keyboardDistanceFromTextField = 15
            IQKeyboardManager.shared.shouldResignOnTouchOutside = true
            

            【讨论】:

              【解决方案11】:

              我会使用一个名为 IQKeyboardManagerSwift 的库。

              您必须在 AppDelegates 的 didFinishWithLaunching 方法中插入一行代码,然后它会将所有必要的功能应用于所有 TextField。

              import IQKeyboardManagerSwift
              
              func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
                  // Override point for customization after application launch.
                  //Following line is all you need and it applies for all TextFields
                  IQKeyboardManager.shared.enable = true
                  return true
              }
              

              【讨论】:

                【解决方案12】:

                因为上面的答案在 Xcode 11 和更高版本的初始工具栏(如UIToolbar())中是旧的,所以每次运行时都会在控制台上抛出一个破坏性约束,比如here,所以请使用 UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35)) 而不是

                示例代码

                            let toolBar =  UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35))
                            toolBar.barStyle = .default
                            toolBar.sizeToFit()
                
                            // Adding Button ToolBar
                            let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneButtonTapped))
                            toolBar.items = [doneButton]
                            toolBar.isUserInteractionEnabled = true
                            textField.inputAccessoryView = toolBar
                

                【讨论】:

                • 这行得通,但是你是怎么想出 35 帧的?
                • 我认为它是默认高度可能你可以配置它来改变
                • 您可以设置任何数字(尝试0到999)。这似乎并没有改变任何东西。
                猜你喜欢
                • 2015-03-18
                • 2021-07-20
                • 1970-01-01
                • 2022-11-01
                • 1970-01-01
                • 1970-01-01
                • 2013-12-10
                • 2014-08-03
                相关资源
                最近更新 更多