如何在数字键盘中添加点? 我希望当我使用通知UIKeyboardDidShowNotification时,UIButton显示在数字键盘键盘的左下方。
这将是按钮的框架:
let dotButton = UIButton(frame: CGRectMake(0, 162, view.frame.width/3, 54))
,
但它必须作为数字键盘键盘的子视图添加,以防止隐藏它,将如何做?
编辑: 我让它看起来像这样
dotButton.addTarget(self, action: "addDot:", forControlEvents: .TouchUpInside)
dotButton.setTitle(".", forState: .Normal)
dotButton.titleLabel?.font = UIFont(name: "Helvetica Neue", size: 25)
dotButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
dispatch_async(dispatch_get_main_queue(), {
let keyboardView:UIView = UIApplication.sharedApplication().windows.last?.subviews.first as! UIView
self.dotButton.frame = CGRectMake(0, keyboardView.frame.size.height-54, self.view.frame.width/3, 54)
keyboardView.addSubview(self.dotButton)
keyboardView.bringSubviewToFront(self.dotButton)
})
但现在我不知道当我点击按钮添加时的方式。在textField中使用方法addDot我不知道如何告诉textField添加一个。再次需要帮助...
EDIT2:
我创建了一个类变量textFieldInEdit:UITextField!
并在func textFieldShouldBeginEditing(textField: UITextField) -> Bool
我执行此操作textFieldInEdit = textField
,现在我的函数addDot
是:
textFieldWhichEdit.text = "\(textFieldWhichEdit.text)."
,
但我现在又遇到了另一个问题..我有不同键盘类型的字段如何检测出现哪个键盘并仅在数字键盘上显示点?
EDIT3:
func textFieldDidBeginEditing(textField: UITextField) {
if(textField.keyboardType.rawValue==4){
textFieldWhichEdit = textField
dotButton.hidden = false
}else{
dotButton.hidden = true
}
}
完成我在数字键盘上做了一个点按钮:) 如果有人知道更好的方法可以写它,我会接受答案:)
答案 0 :(得分:20)
yourTextField.keyboardType = .decimalPad
答案 1 :(得分:0)
将UITextfieldDelegate添加到您的控制器,然后再将文本字段链接到IBOulet(例如tfTest),然后像这样实现shouldChangeCharactersInRange
回调。
@IBOutlet weak var tfTest: UITextField!
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var newText: NSString = textField.text as NSString
newText = newText.stringByReplacingCharactersInRange(range, withString: string)
var isEmptyNew = (newText as String).rangeOfString(".", options: NSStringCompareOptions.allZeros, range: nil, locale: nil)?.isEmpty ?? true
if isEmptyNew {
//change to decimal pad as we allow to add decimal point now
textField.keyboardType = UIKeyboardType.DecimalPad
//refresh responder to change keyboard layout
textField.resignFirstResponder()
textField.becomeFirstResponder()
return true;
}
var isEmptyOld = textField.text.rangeOfString(".", options: NSStringCompareOptions.allZeros, range: nil, locale: nil)?.isEmpty ?? true
//if pressed button is the dot and your text field has already a dot, do not allow this. Normally, this case does not happen cause your keyboard type was changed to number pad before
if string == "." && !isEmptyOld {
return false
} else {
//show just numbers
textField.keyboardType = UIKeyboardType.NumberPad
//refresh responder to change keyboard layout
textField.resignFirstResponder()
textField.becomeFirstResponder()
return true
}
}
为避免小数点分隔符(。或,)的问题,请使用此代码检索小数点分隔符并使用它而不是硬代码值
let df = NSNumberFormatter()
df.locale = NSLocale.currentLocale()
let decimalPoint = df.decimalSeparator ?? "."