Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format UITextField text in real time, while it's being edited?

How can I change value of UITextField text while typing?

In other word:

when I type 1 it should show 1

when I type 10 it should show 10

when I type 100 it should show 100 but

when I type 1000 it should show 1,000

Can you give any idea?

like image 663
user2789934 Avatar asked Sep 18 '13 03:09

user2789934


People also ask

How can I tell if textfield is edited?

You can make this connection in interface builder. In your storyboard, click the assistant editor at the top of the screen (two circles in the middle). Ctrl + Click on the textfield in interface builder. Drag from EditingChanged to inside your view controller class in the assistant view.

What is a UITextField?

An object that displays an editable text area in your interface.

What is a text field on Iphone?

A text field is a UI element that enables the app to get user input.

How do you make a text field non editable in Swift?

You should have a Bool Variable. Set it to 'false' then when the button is pressed you toggle it to 'true'. Depending on its state just run to different methods which essentially allows you to edit or not.


1 Answers

Swift:

Be sure to select the text field input as number pad, then:

In your viewDidLoad:

yourTextField(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)

Then, in that same view controller:

func textFieldDidChange(textField: UITextField) {
        if textField == yourTextField {

            // Some locales use different punctuations.
            var textFormatted = textField.text?.replacingOccurrences(of: ",", with: "")
            textFormatted = textFormatted?.replacingOccurrences(of: ".", with: "")

            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .decimal
            if let text = textFormatted, let textAsInt = Int(text) {
                textField.text = numberFormatter.string(from: NSNumber(value: textAsInt))
            }
        }
    }
like image 95
Juan Boero Avatar answered Oct 23 '22 18:10

Juan Boero