原由
因为需要做到金额的控制,最小金额是角,然后需要判断大于0.5元才可以开启留言功能,所以整理了下 string 的方法,希望能够帮助到需要的人.
开始
@IBOutlet weak var money: UITextField!
@IBOutlet weak var msg: UITextField!
msg.delegate = self
money.delegate = self
money.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
func textFieldDidChange(textField:UITextField){
if textField.text == "" {
button.isEnabled = false
return
}
let index = textField.text!.index(textField.text!.startIndex, offsetBy: 1)
if textField.text?.substring(to: index) == "."{
textField.text = ""
}
if ((textField.text?.range(of: ".")) != nil) {
if (textField.text?.components(separatedBy: ".").count)! > 2 {
textField.text?.remove(at: textField.text!.index(before: textField.text!.endIndex))
}
if (textField.text?.components(separatedBy: ".").count)! > 1 {
let pos = textField.text?.characters.distance(from: textField.text!.startIndex, to: textField.text!.characters.index(of: ".")!)
let str = textField.text?.substring(from: textField.text!.index(textField.text!.startIndex, offsetBy: pos!+1))
if str?.characters.count==2{
textField.text?.remove(at: textField.text!.index(before: textField.text!.endIndex))
}
}
}
button.isEnabled = true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == money {
if textField.text == "" {
return
}
let index = textField.text!.index(textField.text!.startIndex, offsetBy: textField.text!.characters.count-1)
if textField.text?.substring(from: index) == "."{
textField.text?.append("0")
}
let cash = Float(textField.text!)!
if cash >= 0.5 {
msg.isEnabled = true
msg.textColor = UIColor.black
}else{
msg.isEnabled = false
msg.textColor = UIColor.lightGray
}
}
}