新浦京81707con > 注册购买 > 只能输入数字

原标题:只能输入数字

浏览次数:84 时间:2020-05-04

private var IsSetNumberKey: UInt8 = 0private var MaxKey: UInt8 = 0extension 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 > self.max ? "(self.max!)" : text! } } } // 是否属于子集内 func isFiltered(text:String) -> Bool { var cs : NSCharacterSet! cs = NSCharacterSet(charactersInString: text).invertedSet let filtered = self.componentsSeparatedByCharactersInSet.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() }}

本文由新浦京81707con发布于注册购买,转载请注明出处:只能输入数字

关键词: 新浦京81707con 数字 UITextField

上一篇:葡京投注开户iOS_10中UICollectionView和UITableView的变

下一篇:没有了