如何在swift4中验证和删除文本域文本中的空格

时间:2018-03-05 07:01:27

标签: ios swift

guard let text = txtField.text, !text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else{
    let alertController = UIAlertController(title: "New alert!", message:"Please Enter Email Id", preferredStyle: UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
    self.present(alertController, animated: true, completion: nil)
    return
}

如果我使用上面的代码,我只删除textfield中的前导空格。我想删除文本字段文本中包含的空格。

1 个答案:

答案 0 :(得分:-1)

使用以下扩展字符串

  extension String
    {

        func isNumber() -> Bool{
            let numberCharacters = CharacterSet.decimalDigits.inverted
            return !self.isEmpty && self.rangeOfCharacter(from:numberCharacters) == nil
        }
        struct NumberFormat
        {
            static let instance = NumberFormatter()
        }
        var integerValue:Int?
        {
            if self.isEmpty
            {
                return 0
            }
            else
            {
                return (NumberFormat.instance.number(from: self)?.intValue) ?? 0
            }
        }
    }