Answers:
另一个解决方案。如果屏幕上还有其他非数字键盘文本字段,则非常适合。
- (void)viewDidLoad
{
[super viewDidLoad];
UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
numberToolbar.barStyle = UIBarStyleBlackTranslucent;
numberToolbar.items = @[[[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc]initWithTitle:@"Apply" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)]];
[numberToolbar sizeToFit];
numberTextField.inputAccessoryView = numberToolbar;
}
-(void)cancelNumberPad{
[numberTextField resignFirstResponder];
numberTextField.text = @"";
}
-(void)doneWithNumberPad{
NSString *numberFromTheKeyboard = numberTextField.text;
[numberTextField resignFirstResponder];
}
这是Luda对Swift的回答的改编:
在您的UIViewController子类的声明中
let numberToolbar: UIToolbar = UIToolbar()
在ViewDidLoad中放:
numberToolbar.barStyle = UIBarStyle.BlackTranslucent
numberToolbar.items=[
UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "hoopla"),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Apply", style: UIBarButtonItemStyle.Bordered, target: self, action: "boopla")
]
numberToolbar.sizeToFit()
textField.inputAccessoryView = numberToolbar //do it for every relevant textfield if there are more than one
并添加功能hoopla和hoopla(随意选择其他名称,只需相应地在ViewDidLoad中更改选择器名称
func boopla () {
textField.resignFirstResponder()
}
func hoopla () {
textField.text=""
textField.resignFirstResponder()
}
UIBarButtonItemStyle.Bordered
从iOS 8.0开始不推荐使用。UIBarButtonItemStyle.Plain
建议使用。
我见过的技巧是使一个自定义的透明按钮具有整个视图的大小,然后在其单击方法中使文本字段退出第一响应者。因此,用户可以单击字段外的任何位置以关闭键盘。
甲夫特3使用扩展的解决方案。如果您UITextField
的应用程序中有多个数字对象,那么它是理想选择,因为它可以灵活地为每个对象UITextField
确定在点击“完成”或“ 取消”时是否执行自定义操作。
//
// UITextField+DoneCancelToolbar.swift
//
import UIKit
extension UITextField {
func addDoneCancelToolbar(onDone: (target: Any, action: Selector)? = nil, onCancel: (target: Any, action: Selector)? = nil) {
let onCancel = onCancel ?? (target: self, action: #selector(cancelButtonTapped))
let onDone = onDone ?? (target: self, action: #selector(doneButtonTapped))
let toolbar: UIToolbar = UIToolbar()
toolbar.barStyle = .default
toolbar.items = [
UIBarButtonItem(title: "Cancel", style: .plain, target: onCancel.target, action: onCancel.action),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Done", style: .done, target: onDone.target, action: onDone.action)
]
toolbar.sizeToFit()
self.inputAccessoryView = toolbar
}
// Default actions:
func doneButtonTapped() { self.resignFirstResponder() }
func cancelButtonTapped() { self.resignFirstResponder() }
}
使用默认操作的用法示例:
//
// MyViewController.swift
//
@IBOutlet weak var myNumericTextField: UITextField! {
didSet { myNumericTextField?.addDoneCancelToolbar() }
}
使用自定义“完成”操作的用法示例:
//
// MyViewController.swift
//
@IBOutlet weak var myNumericTextField: UITextField! {
didSet {
myNumericTextField?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
func doneButtonTappedForMyNumericTextField() {
print("Done");
myNumericTextField.resignFirstResponder()
}
以下是Luda答案的全面修订,其中包含以下更改:
附件视图的大小自动调整为应用程序框架的宽度
UIBarButtonItemStyleBordered
避免使用不建议使用的常量
“完成”按钮被实例化为 UIBarButtonSystemItemDone
当前,“完成”按钮在附件视图中居中。您可以通过删除相关侧的空格来将其定位在左侧或右侧。
我已经省略了“取消”按钮,因为默认键盘也没有。如果确实要“取消”按钮,建议您将其实例化为a UIBarButtonSystemItemCancel
,并确保您不会在文本字段中丢弃原始值。Luda的答案中实现的“取消”行为(用空字符串覆盖该值)可能不是您想要的。
- (void)viewDidLoad {
[super viewDidLoad];
float appWidth = CGRectGetWidth([UIScreen mainScreen].applicationFrame);
UIToolbar *accessoryView = [[UIToolbar alloc]
initWithFrame:CGRectMake(0, 0, appWidth, 0.1 * appWidth)];
UIBarButtonItem *space = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(selectDoneButton)];
accessoryView.items = @[space, done, space];
self.valueField.inputAccessoryView = accessoryView;
}
- (void)selectDoneButton {
[self.valueField resignFirstResponder];
}
有关构建附件视图的更多信息,请参阅有关数据输入的自定义视图的Apple文档。您可能还希望参考UIToolbar和UIBarButtonItem上的参考页。
[UIScreen mainScreen].applicationFrame
在iOS 9中已弃用。使用[UIScreen mainScreen].bounds
UIKeyboardTypeNumberPad中的解决方案和缺少返回键的效果很好,但前提是屏幕上没有其他非数字键盘文本字段。
我获取了该代码并将其转换为UIViewController,您可以将其简单地子类化以使数字键盘工作。您需要从上面的链接中获取图标。
NumberPadViewController.h:
#import <UIKit/UIKit.h>
@interface NumberPadViewController : UIViewController {
UIImage *numberPadDoneImageNormal;
UIImage *numberPadDoneImageHighlighted;
UIButton *numberPadDoneButton;
}
@property (nonatomic, retain) UIImage *numberPadDoneImageNormal;
@property (nonatomic, retain) UIImage *numberPadDoneImageHighlighted;
@property (nonatomic, retain) UIButton *numberPadDoneButton;
- (IBAction)numberPadDoneButton:(id)sender;
@end
和NumberPadViewController.m:
#import "NumberPadViewController.h"
@implementation NumberPadViewController
@synthesize numberPadDoneImageNormal;
@synthesize numberPadDoneImageHighlighted;
@synthesize numberPadDoneButton;
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if ([super initWithNibName:nibName bundle:nibBundle] == nil)
return nil;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp3.png"];
self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown3.png"];
} else {
self.numberPadDoneImageNormal = [UIImage imageNamed:@"DoneUp.png"];
self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"DoneDown.png"];
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Add listener for keyboard display events
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
// Add listener for all text fields starting to be edited
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldDidBeginEditing:)
name:UITextFieldTextDidBeginEditingNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
}
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextFieldTextDidBeginEditingNotification
object:nil];
[super viewWillDisappear:animated];
}
- (UIView *)findFirstResponderUnder:(UIView *)root {
if (root.isFirstResponder)
return root;
for (UIView *subView in root.subviews) {
UIView *firstResponder = [self findFirstResponderUnder:subView];
if (firstResponder != nil)
return firstResponder;
}
return nil;
}
- (UITextField *)findFirstResponderTextField {
UIResponder *firstResponder = [self findFirstResponderUnder:[self.view window]];
if (![firstResponder isKindOfClass:[UITextField class]])
return nil;
return (UITextField *)firstResponder;
}
- (void)updateKeyboardButtonFor:(UITextField *)textField {
// Remove any previous button
[self.numberPadDoneButton removeFromSuperview];
self.numberPadDoneButton = nil;
// Does the text field use a number pad?
if (textField.keyboardType != UIKeyboardTypeNumberPad)
return;
// If there's no keyboard yet, don't do anything
if ([[[UIApplication sharedApplication] windows] count] < 2)
return;
UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
// Create new custom button
self.numberPadDoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.numberPadDoneButton.frame = CGRectMake(0, 163, 106, 53);
self.numberPadDoneButton.adjustsImageWhenHighlighted = FALSE;
[self.numberPadDoneButton setImage:self.numberPadDoneImageNormal forState:UIControlStateNormal];
[self.numberPadDoneButton setImage:self.numberPadDoneImageHighlighted forState:UIControlStateHighlighted];
[self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
// Locate keyboard view and add button
NSString *keyboardPrefix = [[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2 ? @"<UIPeripheralHost" : @"<UIKeyboard";
for (UIView *subView in keyboardWindow.subviews) {
if ([[subView description] hasPrefix:keyboardPrefix]) {
[subView addSubview:self.numberPadDoneButton];
[self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
break;
}
}
}
- (void)textFieldDidBeginEditing:(NSNotification *)note {
[self updateKeyboardButtonFor:[note object]];
}
- (void)keyboardWillShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}
- (void)keyboardDidShow:(NSNotification *)note {
[self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}
- (IBAction)numberPadDoneButton:(id)sender {
UITextField *textField = [self findFirstResponderTextField];
[textField resignFirstResponder];
}
- (void)dealloc {
[numberPadDoneImageNormal release];
[numberPadDoneImageHighlighted release];
[numberPadDoneButton release];
[super dealloc];
}
@end
请享用。
这是最新的代码。只需在viewController中包含#import“ UIViewController + NumPadReturn.h”。
这是.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UIViewController (NumPadReturn)
@end
还有他们
#import "UIViewController+NumPadReturn.h"
@implementation UIViewController (NumPadReturn)
-(void) viewDidLoad{
// add observer for the respective notifications (depending on the os version)
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
} else {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
}
- (void)keyboardWillShow:(NSNotification *)note {
// if clause is just an additional precaution, you could also dismiss it
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) {
[self addButtonToKeyboard];
}
}
- (void)keyboardDidShow:(NSNotification *)note {
// if clause is just an additional precaution, you could also dismiss it
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
[self addButtonToKeyboard];
}
}
- (void)addButtonToKeyboard {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
[doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];
} else {
[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
}
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
[keyboard addSubview:doneButton];
} else {
if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
}
- (void)doneButton:(id)sender {
NSLog(@"doneButton");
[self.view endEditing:TRUE];
}
@end
如果您有多个数字字段,建议将UITextField子类化以创建一个NumericTextField,该数字始终显示带有完成按钮的数字键盘。然后,只需在Interface Builder中将您的数字字段与此类关联,就不需要任何View Controller中的任何其他代码。以下是我在Xcode 8.0中使用的Swift 3.0类。
class NumericTextField: UITextField {
let numericKbdToolbar = UIToolbar()
// MARK: Initilization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
// Sets up the input accessory view with a Done button that closes the keyboard
func initialize()
{
self.keyboardType = UIKeyboardType.numberPad
numericKbdToolbar.barStyle = UIBarStyle.default
let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let callback = #selector(NumericTextField.finishedEditing)
let donebutton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: callback)
numericKbdToolbar.setItems([space, donebutton], animated: false)
numericKbdToolbar.sizeToFit()
self.inputAccessoryView = numericKbdToolbar
}
// MARK: On Finished Editing Function
func finishedEditing()
{
self.resignFirstResponder()
}
}
斯威夫特4.2
class NumericTextField: UITextField {
let numericKbdToolbar = UIToolbar()
// MARK: Initilization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
// Sets up the input accessory view with a Done button that closes the keyboard
func initialize()
{
self.keyboardType = UIKeyboardType.numberPad
numericKbdToolbar.barStyle = UIBarStyle.default
let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let callback = #selector(NumericTextField.finishedEditing)
let donebutton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: callback)
numericKbdToolbar.setItems([space, donebutton], animated: false)
numericKbdToolbar.sizeToFit()
self.inputAccessoryView = numericKbdToolbar
}
// MARK: On Finished Editing Function
@objc func finishedEditing()
{
self.resignFirstResponder()
}
}
我发现@ user1258240的答案非常简洁,因为这并不像设置returnKeyType
属性那样简单。
只是想为此贡献自己的“可重用”方法:
func SetDoneToolbar(field:UITextField) {
let doneToolbar:UIToolbar = UIToolbar()
doneToolbar.items=[
UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.dismissKeyboard))
]
doneToolbar.sizeToFit()
field.inputAccessoryView = doneToolbar
}
override func viewDidLoad() {
super.viewDidLoad()
SetDoneToolbar(field: UITextField_1)
SetDoneToolbar(field: UITextField_2)
SetDoneToolbar(field: UITextField_3)
SetDoneToolbar(field: UITextField_N)
}
SWIFT 3.0一种不同的风格,使用了一些以前的答案。
func addToolbarToNumberPad()
{
let numberPadToolbar: UIToolbar = UIToolbar()
numberPadToolbar.isTranslucent = true
numberPadToolbar.items=[
UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancelAction)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Custom", style: .done, target: self, action: #selector(self.customAction)),
UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneAction)),
]
numberPadToolbar.sizeToFit()
textField.inputAccessoryView = numberPadToolbar
}
func cancelAction()
{
textField.resignFirstResponder()
}
func customAction()
{
textField.resignFirstResponder()
}
func doneAction()
{
textField.resignFirstResponder()
}
override func viewDidLoad()
{
super.viewDidLoad()
self.addToolbarToNumberPad()
}
在最简单的方法是:
创建自定义的透明按钮,并将其放置在左下的角落,这将有同样的CGSize
在空的空间UIKeyboardTypeNumberPad
。在textField becomeFirstResponder
上切换(显示/隐藏)此按钮,分别单击按钮。
这是我遇到的最简单的解决方案。我已经从《开始iOS 5开发》一书中学到了这一点。
假设数字字段称为numberField
。
在中ViewController
,添加以下方法:
-(IBAction)closeKeyboard:(id)sender;
在中ViewController.m
,添加以下代码:
-(IBAction)closeKeyboard:(id)sender
{
[numberField resignFirstResponder];
}
返回nib
文件。
Utilities
锅。Identity inspector
下Utilities
油锅。View
一次(在nib文件中)。确保您没有单击视图中的任何项目。为了澄清起见,您应该在Class
中看到UIView Identity inspector
。Connection Inspector
。Touch Down
上的箭头File Owner
。(仅供参考... File Owner图标显示在左侧,View
并显示为带有黄色边框的空心立方体。)closeKeyboard
。现在,当您在的背景上单击任意位置时View
,您应该可以关闭键盘。
希望这可以帮助您解决问题。:-)
我对Bryan的解决方案进行了修改,使其更加健壮,因此可以与在同一视图中出现的其他类型的键盘很好地配合使用。在这里描述:
我会在这里解释一下,但是其中大部分是代码,很难理解
对于Swift 2.2,我使用它
func addDoneButtonOnKeyboard() {
let doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.bounds.size.width, 50))
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: #selector(DetailViewController.finishDecimalKeypad))
var items: [UIBarButtonItem]? = [UIBarButtonItem]()
items?.append(flexSpace)
items?.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
self.productPrice.inputAccessoryView=doneToolbar
}
func finishDecimalKeypad() {
self.productPrice?.resignFirstResponder()
}
Swift 2.2 /我使用了Dx_的答案。但是,我希望所有键盘都具有此功能。因此,在我的基类中,我输入了代码:
func addDoneButtonForTextFields(views: [UIView]) {
for view in views {
if let textField = view as? UITextField {
let doneToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.bounds.size.width, 50))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let done = UIBarButtonItem(title: "Done", style: .Done, target: self, action: #selector(dismissKeyboard))
var items = [UIBarButtonItem]()
items.append(flexSpace)
items.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
textField.inputAccessoryView = doneToolbar
} else {
addDoneButtonForTextFields(view.subviews)
}
}
}
func dismissKeyboard() {
dismissKeyboardForTextFields(self.view.subviews)
}
func dismissKeyboardForTextFields(views: [UIView]) {
for view in views {
if let textField = view as? UITextField {
textField.resignFirstResponder()
} else {
dismissKeyboardForTextFields(view.subviews)
}
}
}
然后只需在viewDidLoad中的self.view.subviews上调用addDoneButtonForTextFields(如果使用表视图,则调用willDisplayCell)将Done按钮添加到所有键盘。