How to set the maximum number of value during typing - ios

I have a UITextField, I'd like to restrict the maximum allowed input value in the field to be 1000 .eg (1-1000),If the value in the textfield exceeds above 1000 the textfield should not get the value as input.I have tried the following
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
var newString: String = textField.text.replacingCharacters(in: range, with: string)
var characterSet = CharacterSet(charactersIn: "0123456789,.").inverted
if (newString as NSString).rangeOfCharacter(from: characterSet).location != NSNotFound {
return false
}
return Double(newString) ?? 0.0 < 1000
}

Try this. Hope this will help
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 1001
}

Try extracting the integer value from the textField and check if it is below 1000.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSInteger inte = [textField.text intValue];
if (inte < 1000 && inte > 0)
return NO;
else
return YES;
}

Related

How to make UITextField with combination of password-dot and normal text in ios

Currently my text field is taking input as "111-11-1111" in UITextField. Requirement is to make input as "•••-••-1111". Is this possible to do with the combination of secure text entry and normal text or any other way to accomplish it.
You have to check every text entry in the text field by using
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
this method. And after some particular number of entry, you have append - in your password.
You can implement it like this.
declare a variable as textCount
var textCount = 0
var originalString = String()
Then override the function func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool as below:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "" {
textCount = textCount - 1
var truncated = textField.text?.substring(to: (textField.text?.index(before: (textField.text?.endIndex)!))!)
textField.text = truncated
if textCount == 5 || textCount == 3 {
let truncated = textField.text?.substring(to: (textField.text?.index(before: (textField.text?.endIndex)!))!)
textField.text = truncated
}
truncated = originalString.substring(to: originalString.index(before: originalString.endIndex))
originalString = truncated!
}
else if textCount < 9 {
if textCount == 3 || textCount == 5 {
textField.text = textField.text! + "-"
}
if textCount <= 4 {
textField.text = textField.text! + "*"
originalString.append(string)
}
else {
textField.text = textField.text! + string
originalString.append(string)
}
textCount = textCount + 1
}
print(originalString)
return false
}
Remember to store the text of textfield in delegate itself. Otherwise it will give you wrong value.

How to restrict double/single space for TextField in Swift 3 iOS

I have login page in my iOS app which is developing by Swift language.
In that first letter should not be with single/double space and after user enters text it should allow single space, not allow double space and need to set the limit for text length.
I want to restrict the user while tapping single/double space while starting time entering text and need to allow single space after enters first letter in textfield
I am able to do either one of single/double, but not working as per my requirement.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//for double space restrict
if (range.location > 0 && (textField.text?.characters.count)! > 0) {
//Manually replace the space with your own space, programmatically
//Make sure you update the text caret to reflect the programmatic change to the text view
//Tell Cocoa not to insert its space, because you've just inserted your own
return false
}else {
if textField.tag == 1 || textField.tag == 2 { //restrict text length
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLengthForTextField
}
}
return true
}
Can anyone give suggestions. Thanks
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let rawString = string
let range = rawString.rangeOfCharacter(from: .whitespaces)
if ((textField.text?.characters.count)! == 0 && range != nil)
|| ((textField.text?.characters.count)! > 0 && textField.text?.characters.last == " " && range != nil) {
return false
}
return true
}
Try This Code:
//TextField Validation
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if(textField == UserNameText)
{
if range.location == 0 && string == " "
{
return false
}
return true
}
else if(textField == PasswordText)
{
if range.location == 0 && string == " "
{
return false
}
return true
}
else
{
return true
}
}
It Wont allow users to give space at first letter. For Example if you need to set limit for username field and its limit is 10 characters means use this code:
//TextField Validation
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if(textField == UserNameText)
{
if range.location == 0 && string == " "
{
return false
}
else if range.length + range.location > (self. UserNameText.text?.characters.count)!
{
return false
}
let NewLength = (self.let NewLength = (self.userEmailTxt.text?.characters.count)! - range.length
return NewLength <= 9
}
else if(textField == PasswordText)
{
if range.location == 0 && string == " "
{
return false
}
return true
}
else
{
return true
}
}
try this
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let result = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string
let text = result as String
if (text.range(of: "^(?i)(?![ ])(?!.*[ ]{2})[A-Z. ]*$", options: .regularExpression) != nil) {
return true
}
return false
}
If you need to restrict total length update the regex to ^(?i)(?![ ])(?!.*[ ]{2})[A-Z. ]{1,10}$ for 10 chars. Update the length as required.
Please check this code.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let trimmedString = textField.text?.trimmingCharacters(in: .whitespaces)
if (trimmedString.length == 0)
return false
//for double space restrict
if (range.location > 0 && (textField.text?.characters.count)! > 0) {
//Manually replace the space with your own space, programmatically
//Make sure you update the text caret to reflect the programmatic change to the text view
//Tell Cocoa not to insert its space, because you've just inserted your own
if string.range(of:" ") != nil {
return false
}
return true
}else {
if textField.tag == 1 || textField.tag == 2 { //restrict text length
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLengthForTextField
}
}
return true
}
And your code for restricting textfield length should work fine as it is for textfields with tag 1 & 2.
It works !
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if (string == " " || string == " ") && range.location == 0
{
return false
}
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if range.location == 0 && string == " " {
return false
} else if range.location > 1 && textField.text?.characters.last == " " && string == " " {
return false
}else{
return true
}
}
Hi, Anli please try this it will solve your problem.
Swift 4.1
Just simple with Single line of code you can stop whitespace
For All Textfield
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
textField.text = textField.text?.replacingOccurrences(of: " ", with: "")
return true
}
For Single Textfield
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == txtid
{
textField.text = textField.text?.replacingOccurrences(of: " ", with: "")
}
return true
}
I found answer finally for my requirement
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//for double space restrict
let str = textField.text
if str?.characters.count == 0 && string == " " {
return false
} else if (str?.characters.count)! > 0 {
if str?.characters.last == " " && string == " " {
return false
} else {
if textField.tag == 1 || textField.tag == 2 { //restrict text length
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLengthForTextField
}
}
}
return true
}
Swift 5.0
Only allow single space in textField text change with Error handling:
func textField(textField: UITextField,
shouldChangeCharactersInRange
range: NSRange, replacementString string: String) -> Bool {
let (isValid, errorMessage) = validateSpacesInTextChange(newText: string, existingText: textField.text!, in: NSRange)
return isValid
}
func validateSpacesInTextChange(newText: String,
existingText: String,
in range: NSRange) -> (Bool, errorMessage: String?) {
let range = newText.rangeOfCharacter(from: .whitespaces)
let textNotStartWithSpace = !(existingText.isEmpty && range != nil)
guard textNotStartWithSpace else { return (false, "Space not allowed at the Begning") }
let notContainTwoSpaces = !(!existingText.isEmpty && existingText.last == " " && range != nil)
guard notContainTwoSpaces else { return (false, "Only single space allowed") }
return (true, nil)
}

How to get range of textField text till 6 characters?

I've a UITextField for entering pincode number.
My requirement is when textField character range reach to 6th character then I've to do server validation and I have to put the data in labels. If character range is less than 5 then I will pass nil value.
Below is my code :-
//TextField character range
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == pinCode
{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
if(5 >= newLength)
{
print(newLength)
}
else
{
if newLength == 6
{
serverValidation()
print(textField.text!)
setFields(city: "Ajmer", state: "Rajasthan", country: "India")
return newLength <= 6
}
else
{
return newLength <= 6
}
}
}
return true
}
My problem is when (newLength == 6) then I'm getting textField text of 5 characters only. I mean if suppose zip code is 560068 then text I'm getting 56006 only. (But I've to do server validation in that condition only for 6 characters zip code)
So if (newLength == 6) then how can I get 6 characters in text field, and then I can do server validation here only.
I'm new in swift.
Thanks
shouldChangeCharactersIn will get called prior to getting the actual text in the UITextField
This is how you get the full text from that UITextField
let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
Edit
this is how you can use it
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == pinCode
{
guard let text = textField.text else { return true }
let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
let newLength = newString.characters.count
if(5 >= newLength)
{
print(newLength)
}
else
{
if newLength == 6
{
serverValidation()
print(newString)
setFields(city: "Ajmer", state: "Rajasthan", country: "India")
return newLength <= 6
}
else
{
return newLength <= 6
}
}
}
return true
}
Use TextField delegates method for this.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentCharacterCount = textField.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount+1)
{
return false
}
print(currentCharacterCount)
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= 6 //this will not allow you to enter more than 6 characters
}
After that call
func textFieldDidEndEditing(_ textField: UITextField)
{
print(textField.text!)
setFields(city: "Ajmer", state: "Rajasthan", country: "India")
}
to call this method you can use view.endEditing(true) method.
You should get newlength from textfield.text.length + string.length
then get the text from textfield.text + string.
You can't get new text from textfield.text before call return true.
Try this
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == pinCode
{
guard let text = textField.text else { return true }
var txtAfterUpdate:NSString = textField.text! as NSString
txtAfterUpdate = txtAfterUpdate.stringByReplacingCharactersInRange(range, withString: string)
let txtString = txtAfterUpdate as String
let newLength = txtString.characters.count
if(5 >= newLength)
{
print(newLength)
}
else
{
if newLength == 6
{
print(textField.text!)
setFields(city: "Ajmer", state: "Rajasthan", country: "India")
return newLength <= 6
}
else
{
return newLength <= 6
}
}
}
return true
}

Identical textField functions in swift

I have two identical functions in my ViewController and it seems that neither of them can be renamed.
The first one is used to limit characters and show the number left.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let textField = textField as? UITextField {
if (range.length + range.location > textField.text!.characters.count) {
return false;
}
let newLength = textField.text!.characters.count + string.characters.count - range.length;
cLabel.text = String(25 - newLength)
return newLength <= 25 // To just allow up to … characters
}
return true;
}
The second one enables a button when text is added to the same textField.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (ahskField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
if text.isEmpty{//Checking if the input field is not empty
ahskButton.userInteractionEnabled = false //Enabling the button
ahskButton.enabled = false
} else {
ahskButton.userInteractionEnabled = true //Disabling the button
ahskButton.enabled = true
}
// Return true so the text field will be changed
return true
}
Is there a way to combine them or anything?
You only need one of the shouldChangeCharactersInRange functions.
Put all of your logic in the one method.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let newLength = text.characters.count
if newLength <= 25 {
cLabel.text = String(25 - newLength)
if text.isEmpty { //Checking if the input field is not empty
ahskButton.userInteractionEnabled = false //Enabling the button
ahskButton.enabled = false
} else {
ahskButton.userInteractionEnabled = true //Disabling the button
ahskButton.enabled = true
}
return true;
} else {
return false;
}
}

How to allow only certain set of numbers in a UITextfield in swift 2.0

I am having a UITextField in which i get the month number as input. I am successful in limiting the no of characters to 2 in the UITextField. But i want users to enter only the values from 1 to 12 and none other than that. This has to be done simultaneously when the user types the numbers i.e in func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool. If i use a simple if condition to check the each character and return false in else part the textfield won't allow me to use clear or retype any other character. someone help me.
Set keyboard type as Number Pad
add this
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
if let text = textField.text {
let newStr = (text as NSString)
.stringByReplacingCharactersInRange(range, withString: string)
if newStr.isEmpty {
return true
}
let intvalue = Int(newStr)
return (intvalue >= 0 && intvalue <= 12)
}
return true
}
You can do it simultaneously by checking the TextField value inside shouldChangeCharactersInRange.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let inputStr = textField.text?.stringByAppendingString(string)
let inputInt = Int(inputStr!)
if inputInt > 0 && inputInt < 13 {
return true
} else {
return false
}
}
=> you can Define limite of char like this:-
#define NUMBERS_ONLY #"1234567890"
#define CHARACTER_LIMIT 2
=> and based on define limit char you can use and try it below method :-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool {
// Create an `NSCharacterSet` set which includes everything *but* the digits
let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet
// At every character in this "inverseSet" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.componentsSeparatedByCharactersInSet(inverseSet)
// Rejoin these components
let filtered = components.joinWithSeparator("") // use join("", components) if you are using Swift 1.2
// If the original string is equal to the filtered string, i.e. if no
// inverse characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
}
see this link-- Limit UITextField input to numbers in Swift
Check out this to set Limit the numbers and allow only numbers 0 to 9.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == mobileNumber {
let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
let length = (mobileNumber.text?.count)! + string.count - range.length
return string == numberFiltered && length <= LIMIT
}else if textField == userType {
return false
}
return true
}
I just want to post a more simplified answer based on the previous answers.
Tested on Swift 5.1
Considering that you already set textField.keyboardType = .numberPad, then you can do the following:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
let newStr = (text as NSString).replacingCharacters(in: range, with: string)
guard let intValue = Int(newStr) else {
return true
}
return intValue <= maxNumber // maxNumber: replace with your max number
}
You dont´need to validate that intValue is greater or equal to 0 because in numberPad you can NOT write negative values.

Resources