ios 如何使用Swift将“完成”按钮添加到iOS中的Numpad?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28338981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add "Done" button to Numpad in iOS using Swift?
提问by Dejan Skledar
It works fine with the default keyboard, but I cant get it working with the numpad.
它适用于默认键盘,但我无法使用数字键盘。
Any ideas?
有任何想法吗?
回答by nikolovski
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).
据我所知,你不能在键盘部分添加完成按钮;您必须inputAccessoryView
在UITextField
or 中添加一个UITextView
(如果这是您正在使用的)。
Check the documentation for more info.
查看文档了解更多信息。
Edit: Check this question for an exampleon how to do that.
Edit 2: Similar example in Swift.
Edit 3: Code from edit 2, as link may expire.
编辑 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
斯威夫特 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()
}
回答by Adam Stoller
A Swift-3 Version(of Marko's solution - which worked for me)
Swift-3 版本(Marko 的解决方案 - 对我有用)
(in my case, I have a UITextField identified as textfield
)
(就我而言,我有一个 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()
}
回答by Dejan Atanasov
Swift 5solution using @IBInpectable
and extension. A dropdown will appear under the Attribute Inspector in the Interface Builder for every UITextField in the project.
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()
}
}
回答by Jayprakash Dubey
You can add toolbar with Done button to keyboard.InputAccessoryView
property of textfield can be used to set this toolbar.
您可以将带有“完成”按钮的工具栏添加到键盘。InputAccessoryView
textfield 的属性可用于设置此工具栏。
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
回答by Coder1224
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:
如果你的Done
按钮应该只是关闭数字键盘,那么最简单的版本就是resignFirstResponder
像这样调用选择器:
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:
此代码适用于 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
}
回答by onCompletion
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).
首先让我告诉你一件事,你可以在你的默认键盘上添加一个完成按钮。其实今天我刚刚经历了这个问题并解决了。现成的代码,只需将其放在您的 .swift 类中即可。我正在使用 Xcode 7 并使用 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...
这给了我解决方案...
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.
让它更专业......如果你遵循上面的代码,那么它也会为你提供有效的解决方案,但在这里我试图让它更专业。请注意代码MOD。我用引号留下了以前未使用的代码。
Changes..
变化..
- Creating an Individual Button object
- Setting it to the toolbar
- Reducing the size of the toolbar which was created previously
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 }
- 创建一个单独的按钮对象
- 将其设置到工具栏
- 减小之前创建的工具栏的大小
使用 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 }
It is now giving me the following...Moreover try to match the pictures and find the changes.
它现在给了我以下内容......此外,尝试匹配图片并找到更改。
Thanks.
谢谢。
Hope this helped. Sorry for the long answer.
希望这有帮助。对不起,答案很长。
回答by Mitemmetim
The simplest solution I could find - works with Swift 4.2- hope this helps :)
我能找到的最简单的解决方案 - 适用于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
}
}
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
.
然后你可以在textFieldDidEndEditing
委托方法中处理完成的动作,或者只是在扩展中添加一个自定义方法并在doneButton
.
回答by ilija.trkulja
I would use a library calles IQKeyboardManagerSwift.
我会使用一个名为 IQKeyboardManagerSwift的库。
You simplay have to insert one line of code into AppDelegates didFinishWithLaunching method and it applies all necessary features to all TextFields.
您必须在 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
}
回答by SuryaKantSharma
Because above answers are old in Xcode 11 and above initial toolBar like UIToolbar()
will throw a breaking constraint on console every time like hereyou run so use
UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35))
instead
由于上述的答案在Xcode 11及以上的初始工具栏是老喜欢UIToolbar()
每次都会扔在控制台破约束喜欢在这里你跑这么使用
UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35))
,而不是
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
回答by dicle
According to Marko Nikolovski answer
根据 Marko Nikolovski 的回答
Here is objective-C answer :
这是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];
}