This question already has answers here:
Setting maximum number of characters of `UITextView ` and `UITextField `
(10 answers)
Closed 3 years ago.
I have created the following code where I have an outlet name password, when the user enters a password, I seek to have a limit of more than 5 characters and less than 15. How can I impose this limit within this code?
guard let password = password.text, password.count > 6 else {
self.password.showError(true)
return
}
guard (password == confirmPassword.text) else {
self.confirmPassword.showError(true)
return
}
You can do
guard let password = password.text, password.count > 5 , password.count < 15 else {
self.password.showError(true)
return
}
or
guard (6...15).contains(password.text!.count) else {
self.password.showError(true)
return
}
Also you can use shouldChangeCharactersIn delegate method of the UITextField to limit the count check This
Related
This algorithm or code should work for any # of unique character in a string, by the condition we use to check after.
For instance (If I have a string that I want to know if we have at least 7 unique characters we can do):
let number_of_distinct = Set(some_string.characters).count
if(number_of_distinct >= 7)
{
// yes we have at least 7 unique chars.
}
else
{
// no we don't have at least 7 unique chars.
}
However, this technique seems to be deprecated in Swift 4.2 +, due to the way Strings were updated in Swift 4.0 +.
What would be the new correct approach for this technique mentioned above?
Just remove the .characters
let number_of_distinct = Set(some_string).count
if(number_of_distinct >= 7)
{
print("yes")
// yes we have at least 7 unique chars.
}
else
{
print("no")
// no we don't have at least 7 unique chars.
}
You can also do this without using the Set.
func printUniqueCompleteSubString(from string: String) {
var uniquString = ""
uniquString = string.reduce(uniquString) { (result, char) -> String in
if result.contains(char) {
return result
}
else {
return result + String.init(char)
}
}
print("Unique String is:", uniquString)
}
This question already has answers here:
Set the maximum character length of a UITextField in Swift
(22 answers)
How to limit the textfield entry to 2 decimal places in swift 4?
(8 answers)
Closed 4 years ago.
How can I change a UITextField, that the User can just add one . and only two digits after the . -> Decimal Number with two digits after the poi^nt.
Use UITextFieldDelegate
// MARK:- TEXTFIELD DELEGATE
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
let countdots = (txf_Amount.text?.components(separatedBy: ".").count)! - 1
if countdots > 0 && string == "."
{
return false
}
let MAX_BEFORE_DECIMAL_DIGITS = 7
let MAX_AFTER_DECIMAL_DIGITS = 3
let computationString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
// Take number of digits present after the decimal point.
let arrayOfSubStrings = computationString.components(separatedBy: ".")
if arrayOfSubStrings.count == 1 && computationString.characters.count > MAX_BEFORE_DECIMAL_DIGITS {
return false
} else if arrayOfSubStrings.count == 2 {
let stringPostDecimal = arrayOfSubStrings[1]
return stringPostDecimal.characters.count <= MAX_AFTER_DECIMAL_DIGITS
}
return true
}
This question already has answers here:
How do I prevent my text from displaying Optional() in the Swift interpolation?
(3 answers)
Closed 5 years ago.
That's my code
let temperature = String(describing: Int(incomeTemp.text!))
celcjuszScore.text = "\(temperature)"
print(temperature)
Whent I am pushing a button, the result of print is "Optional(32)" (When I am writing 32 in incomeTemp). I would like to have "Optional" removed and only "32" should stay.
Just unwrap it.
if let temperature = Int(incomeTemp.text!) {
celcjuszScore.text = "\(temperature)"
print(temperature)
}
Remove the optional when converting text to number: Int(incomeTemp.text!) ?? 0.
Or solve the error explicitly:
if let temperature = Int(incomeTemp.text ?? "") {
celcjuszScore.text = "\(temperature)"
} else {
celcjuszScore.text = "Invalid temperature"
}
This question already has an answer here:
Error "{ expected after if statement"
(1 answer)
Closed 6 years ago.
Pardon me for beginner's question, Why this code got complained about { expected after if, the braces are already there
var years = Int(edtYears.text!)
if years !=nil {
//do something
}else {
//...
}
Thanks
You need to add space between both side of condition like if years != nil { or you can also write without space but the both side if years!=nil {
var years = Int("")
if years != nil {
//do something
}else {
//...
}
Never do like this. Make sure you do optional chaining otherwise you will surely get a crash.
if let text = edtYears.text, let convertToInt = Int(text){
print("Int \(convertToInt)")
}else{
print("Cannot convert")
}
This question already has answers here:
UITextField for Phone Number
(25 answers)
Closed 8 years ago.
I'm creating an iPhone app using Swift. I'm trying to setup a textfield in which the user can enter a phone number that automatically becomes formatted EXACTLY like it does in the built-in Contacts app as it is typed. I'm hoping xcode has built-in methods for doing this.
As an alternative, I created my own code that would add and delete brackets, dashes, etc as the user types and backspaces, but this quickly became problematic if the user was to move the curser away from the end of the entered text. In the Contacts app, if the cursor is moved just after a bracket and the user hits backspace, it deletes not just the bracket but rather the number preceding it. I'm not sure if this is done with some built-in formatting method or if perhaps there is code that replicates the text shown with brackets, dashes, etc removed and reads the position of the cursor, then calculates what the new string should be, and adds new brackets, dashes, etc.
Specifically, I'd like to know:
1) Is there a built-in method to format text to look like a phone number exactly as is done in the Contacts app?
2) If there is no built-in method, can someone tell me how I can have Swift read in the cursor position?
Thanks!
There is no built-in way to do this. Here's one implementation that uses the UITextField's shouldChangeCharactersInRange method:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if textField == phoneTextField
{
var newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
var components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
var decimalString = "".join(components) as NSString
var length = decimalString.length
var hasLeadingOne = length > 0 && decimalString.characterAtIndex(0) == (1 as unichar)
if length == 0 || (length > 10 && !hasLeadingOne) || length > 11
{
var newLength = (textField.text as NSString).length + (string as NSString).length - range.length as Int
return (newLength > 10) ? false : true
}
var index = 0 as Int
var formattedString = NSMutableString()
if hasLeadingOne
{
formattedString.appendString("1 ")
index += 1
}
if (length - index) > 3
{
var areaCode = decimalString.substringWithRange(NSMakeRange(index, 3))
formattedString.appendFormat("(%#)", areaCode)
index += 3
}
if length - index > 3
{
var prefix = decimalString.substringWithRange(NSMakeRange(index, 3))
formattedString.appendFormat("%#-", prefix)
index += 3
}
var remainder = decimalString.substringFromIndex(index)
formattedString.appendString(remainder)
textField.text = formattedString
return false
}
else
{
return true
}
}
As previously answered in this thread: UITextField for Phone Number