如何使用Swift在iOS中将“完成”按钮添加到Numpad?


77

它可以在默认键盘上正常工作,但是我无法在数字键盘上使用它。

有任何想法吗?



2
我对创建新键盘不感兴趣,我只想向UIToolBar添加一个按钮,然后将其作为inputAccessoryView添加到textField中,例如:stackoverflow.com/a/11382044/3207979,但是我还没有想到然而,如何做到这一点的迅速..
德扬Skledar

可以通过向默认键盘添加自定义按钮来代替自定义键盘或工具栏。请参阅此答案
纳粹

使用情节
提要的

Answers:


96

据我所知,您不能在键盘部分上添加“完成”按钮。您必须inputAccessoryViewUITextFieldUITextView(如果您使用的是)上添加一个。

查看文档以获取更多信息

编辑:检查此问题以获取有关如何执行此操作的示例

编辑2Swift中的类似示例

编辑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()
    }

完美的作品。快速简便的实施。谢谢!
Octavio AntonioCedeño17年

3
您可以更改为该按钮,而不必本地化按钮:完成:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.done,target:self,action:#selector(self.doneButtonAction))
Zeezer

59

一个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()
}

46

Swift 5解决方案的使用@IBInpectable和扩展。对于项目中的每个UITextField,将在“界面构建器”的“属性检查器”下显示一个下拉列表。

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

2
很棒的答案。我希望每个人都在这里滚动。
biomiker

1
好答案。我在代码中使用了它
Firas Shrourou

15

您可以使用“完成”按钮将工具栏添加到键盘。 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

屏幕截图


5

如果您的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
}

3

首先,让我告诉您一件事,您可以在默认键盘上添加完成按钮。实际上,今天我只是解决了这个问题并解决了。现成的代码,只需将其放在您的.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

我能找到的最简单的解决方案-与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


优秀,简单,优雅的解决方案!
MrMins

3

因为上面的答案在Xcode 11中都是古老的,而在初始的ToolBar之上,likeUIToolbar()每次都会在控制台上抛出破坏性约束,就像您在此处运行的那样,因此请 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帧的呢?
geohei

1
我认为这是默认高度,您可以对其进行配置以进行更改
SuryaKantSharma

您可以设置任何数字(尝试0到999)。看来这似乎并没有改变任何东西。
geohei

2

根据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];
}

2

您可以创建一个自定义类。我正在使用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()
    }
}

1
这为我工作了。只需将其复制并粘贴到.swift文件的底部,然后使用:textfieldOutput.addDoneButtonOnKeyboard()到ViewDidLoad中。谢谢!
David_2877

2

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

您必须在simplay中将一行代码插入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
}

0

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

IQKeyboardManager

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

IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.enableAutoToolbar = true
IQKeyboardManager.shared.keyboardDistanceFromTextField = 15
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.