如何添加“完成”使用SWIFT在iOS中进行numpad的按钮?

发布于 2025-02-13 08:07:16 字数 51 浏览 2 评论 0原文

默认键盘可以正常工作,但是我无法与NumPad一起使用。

有什么想法吗?

It works fine with the default keyboard, but I cant get it working with the numpad.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

一绘本一梦想 2025-02-20 08:07:16

据我所知,您无法在键盘部分上添加完成按钮;您将inputAccessoryView添加到uitextfielduitextview(如果您正在使用的话)。

检查文档有关更多信息

编辑:检查这个问题以示例如何做。

编辑2 :相似 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()
    }

As far as I know, you can't add the Done button on the keyboard part; you'd have add a inputAccessoryView to the UITextField or UITextView (if that's what you're using).

Check the documentation for more info.

Edit: Check this question for an example on how to do that.

Edit 2: Similar example in Swift.

Edit 3: Code from edit 2, as link may expire.

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()
    }
樱桃奶球 2025-02-20 08:07:16

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

Swift 5 solution using @IBInpectable and extension. A dropdown will appear under the Attribute Inspector in the Interface Builder for every UITextField in the project.

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()
    }
}
千年*琉璃梦 2025-02-20 08:07:16

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

A Swift-3 Version (of Marko's solution - which worked for me)

(in my case, I have a UITextField identified as 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()
}
酒绊 2025-02-20 08:07:16

您可以添加带有完成按钮的工具栏。

以下是我在情况下使用的代码

//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

”屏幕快照

You can add toolbar with Done button to keyboard. InputAccessoryView property of textfield can be used to set this toolbar.

Below is code that I’ve used in my case

//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

Screenshot

秉烛思 2025-02-20 08:07:16

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

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

The simplest solution I could find - works with Swift 4.2 - hope this helps :)

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

Then you can handle the done action in the textFieldDidEndEditing delegate method or just add a custom method to the extension and set it in the selector of the doneButton.

oО清风挽发oО 2025-02-20 08:07:16

如果您的完成按钮应该仅关闭编号板,则最简单的版本是调用wisefirstresponder作为选择器:

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
}

If your Done button is supposed to just close the numberpad, then the simplest version would be to call resignFirstResponder as the selector like this:

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

This code works in iOS9 and Swift 2, I am using it in my app:

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
}
陌路黄昏 2025-02-20 08:07:16

首先,让我告诉您一件事,您可以在默认键盘上添加完成按钮。实际上,今天我只是解决了这个问题并解决了。现成的代码,只需将其放在您的.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 textfieldshouldbegineding(textfield:uitextfield) - > bool {
    令KeyboardDoneButtonshow = UitoolBar(帧:CgrectMake(200,200,self.view.frame.frame.size.width,30))
    
    // self.view.frame.size.height/17
    键盘donebuttonshow.barstyle = uibarstyle .blacktranslucent
    让按钮:uibutton = uibutton()
    button.frame = cgrectMake(0,0,65,20)
    button.settitle(“完成”,forstate:uicontrolstate .Normal)
    button.addtarget(自我,操作:selector(“ textfieldshouldShouldReturn:”),forcontrolevents:uicontrolevents .touchupinside)
    button.backgroundColor = uicolor .clearcolor()
    //让DoneButton = UibarbuttonItem(标题:“ DONE”,样式:uibarbuttonitemstyle.done,目标:自我,动作:选择器:selector(“ textfieldshouldshouldretrunter:”))
    让DONE DROBTON:uibarbuttonItem = uibarbuttonitem()
    DoneButton.customView =按钮
    LETENEDENTEMPACE = UIBARBUTTONITEM(BarbuttonSystemitem:Uibarbuttonsystemitem.fixedSpace,目标:nil,action:nil)
    否定空间= -10.0
    令flexspace = uibarbuttonItem(barbuttonsystemitem:uibarbuttonsystemitem.flexiblespace,目标:nil,行动:nil)
    //donebutton.tintcolor = uicolor .yellowcolor()
    令工具栏= [FlexSpace,DoneButton,负式空间]
    keyboarddonebuttonshow.setitems(Toolbarbutton,动画:false)
    utlettextfieldtime.inputaccessoryview = keyboardDoneButtonshow
    返回true
    }
     

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

谢谢。

希望这有所帮助。对不起,回答很长。

First of all let me tell you one thing that You Can ADD A Done Button On Your Default KeyBoard. Actually today I just went through this problem and solved. Ready Made Code, just place this on your .swift class. I am using Xcode 7 and testing this using iPad Retina(ios 9).

Anyway no more talk here is the code.

  //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
   }
}

Which is giving me the solution as...

enter image description here

One more thing I just wanna tell you that this is the working solution which I have used on my recent project. I have posted this because there is no working solution available for this problem. Working Code and explanation as promised.

EDIT :-

Making it more professional...If you are following the above code then also it will give you the working solution but here I am trying to make it more Professional. Please notice the code MOD. I left the previous unused code with quote.

Changes..

  1. Creating an Individual Button object
  2. Setting it to the toolbar
  3. Reducing the size of the toolbar which was created previously
  4. Positioning the custom button to the left of the screen using FlexSpace and 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
    }
    

It is now giving me the following...Moreover try to match the pictures and find the changes.

enter image description here

Thanks.

Hope this helped. Sorry for the long answer.

挥剑断情 2025-02-20 08:07:16

我将使用库calles iqkeyboardmanagerswift

Simplay必须将一行代码插入AppDelegates DID FinishWithLaunching方法,并且它将所有必要的功能应用于所有Textfields。

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
}

I would use a library calles IQKeyboardManagerSwift.

You simplay have to insert one line of code into AppDelegates didFinishWithLaunching method and it applies all necessary features to all TextFields.

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
}
街道布景 2025-02-20 08:07:16

因为上述答案在Xcode 11中及以上是最初的工具栏,例如uitoolbar()每次都会像在这里您运行
uitoolbar(框架:cgrect(x:0,y:0,width:view.frame.size.width,高度: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

Because above answers are old in Xcode 11 and above initial toolBar like UIToolbar() will throw a breaking constraint on console every time like here you run so use
UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35)) instead

Sample code

            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
傾旎 2025-02-20 08:07:16

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

According to Marko Nikolovski answer

Here is objective-C answer :

- (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];
}
辞取 2025-02-20 08:07:16

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

You can create a custom class. I'm using 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()
    }
}
过潦 2025-02-20 08:07:16

在任何键盘上添加“完成”按钮的简单简便方法是添加Universal Library

iqkeyboard manager

AppDelegate在应用程序(_应用程序:uiapplication,did finishlaunchingwithoptions。

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

simple and easy way to add "DONE" button on any keyboard is add universal library

IQKeyboardManager

add below code in appdelegate at application(_ application: UIApplication, didFinishLaunchingWithOptions.

IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.enableAutoToolbar = true
IQKeyboardManager.shared.keyboardDistanceFromTextField = 15
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文