如何限制文本字段在swift中仅接受十进制值

时间:2017-06-01 10:25:48

标签: ios swift ipad swift3 uitextfield

我想在文本字段中仅接受小数值。

以下代码只允许我输入数字和'。'但我们可以输入多个'。'

我怎样才能将它限制为一个'。'或者如何限制文本字段仅接受swift 3.1中的十进制值

let aSet = NSCharacterSet(charactersIn:"0123456789.").inverted
let compSepByCharInSet = r_Qty_txt.text?.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet?.joined(separator: "")

我的目标设备是iPad。

listViewCell.swift代码

import UIKit

class listViewCell: UITableViewCell, UITextFieldDelegate {

var delegate: CellInfoDelegate?

@IBOutlet weak var desc_lbl: UILabel!
@IBOutlet weak var openQty_lbl: UILabel!
@IBOutlet weak var r_Qty_txt: UITextField!
@IBOutlet weak var itemId_lbl: UILabel!

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let newString: String = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let expression: String = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
    //var error: Error? = nil
    let regex = try? NSRegularExpression(pattern: expression, options: .caseInsensitive)
    let numberOfMatches: Int = (regex?.numberOfMatches(in: newString, options: [], range: NSRange(location: 0, length: (newString.characters.count ))))!
    return numberOfMatches != 0
}


public func configure(textVal: String?, placeholder: String){
    r_Qty_txt.text = textVal
    r_Qty_txt.placeholder = placeholder

    r_Qty_txt.accessibilityValue = textVal
    r_Qty_txt.accessibilityLabel = placeholder

}

@IBAction func QtyEntered(_ sender: UITextField) {
    print("Value Added \(String(describing: r_Qty_txt.text)) and \(String(describing: openQty_lbl.text))")
    if (r_Qty_txt.text!.isEmpty) {

    }else if(Int(r_Qty_txt.text!)! > Int(openQty_lbl.text!)!){
        print("Not Allowed")
        r_Qty_txt.text = nil
    }
}

override func awakeFromNib() {
    r_Qty_txt.delegate = self
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

2 个答案:

答案 0 :(得分:2)

如果你想在你的textField中只允许使用十进制数,你就可以这样做,不需要比较任何其他内容。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text != "" || string != "" {
        let res = (textField.text ?? "") + string
        return Double(res) != nil
    }
    return true
}

答案 1 :(得分:1)

从属性检查器中仅为数字选择键盘类型。

http://jmsyst.com/libs/serializer/master/reference/annotations#handlercallback

并仅使用委托一个小数点(。)

func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool
{
    let countdots = textField.text.componentsSeparatedByString(".").count - 1

    if countdots > 0 && string == "."
    {
        return false
    }
    return true
}