UITextField 格式化,只能输入数字

最近工程用到输入验证,尤其是数字,就算设置为数字键盘,依然会有第三方键盘还有复制粘贴这些问题,导致非数字的输入,所以自定义了格式化控件,暂时只用到数字,以后还可以继续扩展

private var IsSetNumberKey: UInt8 = 0
private var MaxKey: UInt8 = 0
extension UITextField {
    // 是否设置数字格式 
    public var isSetNumber: Bool? {
        get {
            return (objc_getAssociatedObject(self, &IsSetNumberKey) as? Bool) ?? false
        }
        set {
            objc_setAssociatedObject(self, &IsSetNumberKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    // 设置最大数
    public var max: Double? {
        get {
            return (objc_getAssociatedObject(self, &MaxKey) as? Double)
        }
        set {
            objc_setAssociatedObject(self, &MaxKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    // 输入验证
    func isNum(range: NSRange,string: String) -> Bool {
        if self.isSetNumber! {
            let text = self.text ?? ""
            if string.componentsSeparatedByString(".").count > 1 {
                if text.componentsSeparatedByString(".").count > 1 {
                    return false
                }
            }
            return string.isFiltered("0123456789.")
        }
        return true
    }
    // 格式化,为了去除多余的.
    func setNum() {
        if self.isSetNumber! {
            var text = (self.text == nil || self.text == "") ? "0":self.text
            if text!.hasSuffix(".") {
                text! = NSString(string: text!).stringByReplacingCharactersInRange(NSMakeRange(text!.characters.count-1, 1), withString: "")
                self.text = text!
            }
            if max != nil {
                self.text = Double(text!) > self.max ? "\(self.max!)" : text!
            }
        }
    }
    // 是否属于子集内
    func isFiltered(text:String) -> Bool {
        var cs : NSCharacterSet!
        cs = NSCharacterSet(charactersInString: text).invertedSet
        let filtered = self.componentsSeparatedByCharactersInSet(cs).joinWithSeparator("")
        let basicTest = self == filtered
        if(!basicTest) {
            return false
        }
        return true
    }
}
// 自定义输入数字控件
class ZMDDoubleTextField: UITextField,UITextFieldDelegate {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isSetNumber = true
        self.keyboardType = .NumberPad
        self.delegate = self
    }
    // 从xib或者storeboard 实例
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.isSetNumber = true
        self.delegate = self
        self.keyboardType = .NumberPad
    }
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        return textField.isNum(range, string: string)  
    }
    func textFieldDidEndEditing(textField: UITextField) {
        textField.setNum()
    }
}

你可能感兴趣的:(UITextField 格式化,只能输入数字)