Real-time validation of a textField

Asked

Viewed 120 times

0

I have an application in Swift 1 for ipad, would like to remove or not accept the entry of "." in my textField. It is like Numberpad. I found some solutions here but none at Swift.

  • 1

    [OFF] Curiosity not related to the question: Why you are still using Swift 1?

1 answer

0

If you need to make a field for input of integer numbers you can simply subclass Uitextfield and customize your field within the awakeFromNib method and you can also add addTarget to Uicontrolevents there. editingChanged is a method for filtering characters that are not digits. Follow the link from answer that I have posted/updated in the OS in English:

import UIKit

class IntegerField: UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        keyboardType = .numberPad
        textAlignment = .right
        editingChanged()
    }
    func editingChanged() {
        text = Formatter.decimal.string(from: string.numbers.integer as NSNumber)
    }
}

struct Formatter {
    static let decimal = NumberFormatter(numberStyle: .decimal)
}

extension UITextField {
    var string: String { return text ?? "" }
}

extension String {
    var numbers: String { return components(separatedBy: Numbers.characterSet.inverted).joined() }
    var integer: Int { return Int(numbers) ?? 0 }
}

struct Numbers { static let characterSet = CharacterSet(charactersIn: "0123456789") }

extension NumberFormatter {
    convenience init(numberStyle: NumberFormatter.Style) {
        self.init()
        self.numberStyle = numberStyle
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.