我在我的UITextFields上将UIKeyboardType设置为UIKeyboardTypeNumberPad。但是,这只允许用户输入正整数。我需要用户能够输入负整数或正整数。 UIKeyboardType是否与UIKeyboardTypeNumberPad相同但是还包含“ - ”(减号)符号,如果没有,我可以创建它吗?
感谢。
答案 0 :(得分:13)
虽然很烦人,但没有这样的系统键盘可用。除了创建自定义键盘之外,最好的选择是UIKeyboardTypeNumbersAndPunctuation
,并进行验证以强制执行有效的数字输入。
答案 1 :(得分:3)
这是Swift中的一个版本,具有+/-按钮和数字键盘的“清除并完成”按钮。
extension UITextField {
func addNumericAccessory(addPlusMinus: Bool) {
let numberToolbar = UIToolbar()
numberToolbar.barStyle = UIBarStyle.default
var accessories : [UIBarButtonItem] = []
if addPlusMinus {
accessories.append(UIBarButtonItem(title: "+/-", style: UIBarButtonItem.Style.plain, target: self, action: #selector(plusMinusPressed)))
accessories.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) //add padding after
}
accessories.append(UIBarButtonItem(title: "Clear", style: UIBarButtonItem.Style.plain, target: self, action: #selector(numberPadClear)))
accessories.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) //add padding space
accessories.append(UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(numberPadDone)))
numberToolbar.items = accessories
numberToolbar.sizeToFit()
inputAccessoryView = numberToolbar
}
@objc func numberPadDone() {
self.resignFirstResponder()
}
@objc func numberPadClear() {
self.text = ""
}
@objc func plusMinusPressed() {
guard let currentText = self.text else {
return
}
if currentText.hasPrefix("-") {
let offsetIndex = currentText.index(currentText.startIndex, offsetBy: 1)
let substring = currentText[offsetIndex...] //remove first character
self.text = String(substring)
}
else {
self.text = "-" + currentText
}
}
}
答案 2 :(得分:2)
添加减号作为accesoryView,您需要将textField作为属性,在此示例中,此属性为:myTextField;
您需要在创建myTextField后添加此代码,b.e。在viewDidLoad中:
UIView *inputAccesoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
// It´s good idea a view under the button in order to change the color...more custom option
inputAccesoryView.backgroundColor = [UIColor whiteColor];
UIButton *minusButton = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-150)/2, 5, 150, 30)];
// configure the button here... you choose.
[minusButton setTitle:@"-" forState:UIControlStateNormal];
[minusButton addTarget:self action:@selector(changeNumberSing) forControlEvents:UIControlEventTouchUpInside];
[inputAccesoryView addSubview:minusButton];
self.myTextField.inputAccessoryView = inputAccesoryView;
在viewController中添加此按钮的方法:
-(void)changeNumberSing
{
if ([self.myTextField.text hasPrefix:@"-"])
{
self.myTextField.text = [self.myTextField.text substringFromIndex:1];
}else
{
self.myTextField.text = [NSString stringWithFormat:@"-%@",self.myTextField.text];
}
}