PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

[FIXED] How to limit the text field to be able to enter only decimal digits?

 August 12, 2022     decimal, ios, swift, uitextfield, validation     No comments   

Issue

I have the app for Celectial navigation calculations, I have converted in code textField.text to Double, but some times app crashing if user input some fields like "1.0" and some like "1", in result app crashing because can't deduct Int and Double, to be sure I want to restrict user to input only decimal digits "1.0". The best way for me is to code something like if the user enters for example "1" automatically after pressing the done button, add ".0" to get 1.0?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = "-1234567890."
        let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
        let typedCharactersSet = CharacterSet(charactersIn: string)
        return allowedCharacterSet.isSuperset(of: typedCharactersSet)

    }




     func TextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = latDegTextField.text else { return true }
        let count = text.count + string.count - range.length
        return count == 2
    }

Solution

Use this code :-

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //Will prevent user from entering space as first character
        let enteredCharString = "\(textField.text ?? "")\(string )"
        if enteredCharString.trimmingCharacters(in: .whitespaces).count == 0 {
            return false
        }
        switch textField {
        case txt_Ammount:
            if txt_Ammount.text != "" || string != "" {
                let res = (txt_Ammount.text ?? "") + string
                return Double(res) != nil
            }
        default:
            true
        }



        return true

    }


Answered By - NavinBagul
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing