[英]text formatting text field swift
I am trying to format a text field. 我正在尝试格式化文本字段。 It should contain numbers and must always end in "00".
它应该包含数字,并且必须始终以“ 00”结尾。 If the User 10 enter the text should end up in 10.00, always.
如果用户10输入,则文本应始终为10.00。 I tried this but not getting the results he wanted:
我尝试了此操作,但未获得他想要的结果:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
let textValue = Double(textField.text!)
textField.text = numberFormatter.stringFromNumber(textValue!)
return true
}
now it is chash 现在很破
Starting with the code you present, the reason that it crashes is given by the compiler: "fatal error: unexpectedly found nil while unwrapping an Optional value." 从您提供的代码开始,其崩溃的原因由编译器给出:“致命错误:在解开Optional值时意外发现nil。” The
textValue
is nil
because when the first character is introduced the textField
is empty, and the result of getting a double
from an empty string is nil
. textValue
为nil
因为在引入第一个字符时textField
为空,并且从空字符串中获取double
的结果为nil
。
Note also that even if everything were correct you should return false
so the changes you made in the textField
can take place. 还要注意,即使一切正确,您也应该返回
false
以便可以在textField
中进行更改。
Regarding a solution, I'm not sure if I understood your question, so I present here two solutions: 关于解决方案,我不确定是否理解您的问题,因此在此提出两种解决方案:
The user enters 1 and it displays 1.00. 用户输入1并显示1.00。 Note that this way it is impossible to have something like this: 10.50 or 2.35.
请注意,用这种方法不可能有这样的东西:10.50或2.35。
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var originalString = textField.text!
var replacedString: String!
// Deleting text
if string.isEmpty {
// Delete the first caracter before .00
let loc = originalString.characters.count - 4
let range = NSMakeRange(loc, 1)
replacedString = (originalString as NSString).stringByReplacingCharactersInRange(range, withString: "")
if replacedString == ".00" {
textField.text = ""
return false
}
replacedString = formatNumberFromString(replacedString)
textField.text = replacedString
return false
}
if originalString.isEmpty {
// If we want to avoid having zeros before the dot. Ex.: 000.00
if string == "0" {
return false
}
replacedString = string + ".00"
textField.text = replacedString
return false
} else {
// Original string has the format ###.00
originalString = originalString.stringByReplacingOccurrencesOfString(".00", withString: "")
replacedString = originalString + string + ".00"
// Format number
replacedString = formatNumberFromString(replacedString)
textField.text = replacedString
return false
}
// For any other UITextField's
return true
}
func formatNumberFromString(var stringNumber: String) -> String {
if stringNumber.isEmpty {
return ""
}
// Replace any formatting commas
stringNumber = stringNumber.stringByReplacingOccurrencesOfString(",", withString: "")
let doubleFromString = Double(stringNumber)
let finalString = numberFormatter.stringFromNumber(doubleFromString!)
return finalString!
}
If the user enters 1 it displays 0.01. 如果用户输入1,则显示0.01。 Next 3 and it displays 0.13, 7 -> 1.37 and so on.
接下来的3,并显示0.13、7-> 1.37,依此类推。
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var originalString = textField.text
// Replace any formatting commas
originalString = originalString!.stringByReplacingOccurrencesOfString(",", withString: "")
var doubleFromString: Double!
if originalString!.isEmpty {
originalString = string
doubleFromString = Double(originalString!)
doubleFromString! /= 100
} else {
if string.isEmpty {
// Replace the last character for 0
let loc = originalString!.characters.count - 1
let range = NSMakeRange(loc, 1)
let newString = (originalString! as NSString).stringByReplacingCharactersInRange(range, withString: "0")
doubleFromString = Double(newString)
doubleFromString! /= 10
} else {
originalString = originalString! + string
doubleFromString = Double(originalString!)
doubleFromString! *= 10
}
}
let finalString = numberFormatter.stringFromNumber(doubleFromString)
textField.text = finalString
return false
}
Note also that I moved the NSNumberFormatter
initializer outside these functions as it is a time consuming operation. 还要注意,我将
NSNumberFormatter
初始化程序移到了这些函数之外,因为这是一项耗时的操作。
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
let numberFormatter = NSNumberFormatter()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.textField.delegate = self
numberFormatter.numberStyle = .DecimalStyle
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
}
// ...
}
I hope this helps with your problem. 希望这对您的问题有所帮助。
Would suggest converting the text to an actual number and use an NSNumberFormatter
and set minimumFractionDigits
and maximumFractionDigits
. 建议将文本转换为实际数,并使用
NSNumberFormatter
并设置minimumFractionDigits
和maximumFractionDigits
。 An example: 一个例子:
let numberFormatter = NSNumberFormatter()
numberFormatter.locale = NSLocale.currentLocale()
numberFormatter.numberStyle = .DecimalStyle
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
textField.text = numberFormatter.stringFromNumber(#your number#)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.