gpt4 book ai didi

ios - 是否有像数字键盘但允许负数的 UITextField 键盘类型?

转载 作者:技术小花猫 更新时间:2023-10-29 10:46:38 45 4
gpt4 key购买 nike

我在我的 UITextFields 上将 UIKeyboardType 设置为 UIKeyboardTypeNumberPad。但是,这只允许用户输入正整数。我需要用户能够输入负整数或正整数。是否有与 UIKeyboardTypeNumberPad 相同但还包含“-”(减号)符号的 UIKeyboardType,如果没有,我是否可以创建它?

谢谢。

最佳答案

这是一个 Swift 版本,它有一个 +/- 按钮,还有一个用于数字键盘的清除和完成按钮。

numeric keyboard screenshot

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

}

关于ios - 是否有像数字键盘但允许负数的 UITextField 键盘类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27272121/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com