Reputation: 39389
I have two UITextInput controls that I want to count the number of characters in.
For context, I have two inputs: one for email address and one for password. I also have a “Login” button. The button is inactive by default, but as soon as at least one character is entered into both inputs, I’ll programatically enable the button. This is to prevent login attempts until the user has entered a value in both fields.
So far, I’m using this approach:
if count(emailInput.text) > 0 && count(passwordInput.text) > 0 {
// Enable button
} else {
// Disable button
}
Is using the count()
function acceptable? Or is there a better way? As I recall there are some gotchas with checking the length of strings in iOS/Swift.
Upvotes: 3
Views: 19879
Reputation: 1204
Swift 4
emailInput.text!.count
Swift 2
self.emailInput.text!.characters.count
but if you need to do something more elegant you can create an extension like this
Nowadays, after putting count
directly on text
property my guess is to use this directly without extension, but if you like to isolate this sort of things, go ahead!.
extension UITextField {
var count:Int {
get{
return emailInput.text?.count ?? 0
}
}
}
Upvotes: 3
Reputation: 875
if((emailInput.text!.characters.count) > 0 && (passwordInput.text!.characters.count) > 0) {
// Enable button
} else {
// Disable button
}
Upvotes: 5
Reputation: 7549
For me personally the following code has worked fine in past.
if (!emailInput.text.isEmpty && !passwordInput.text.isEmpty) {
// enable button
} else {
// disable button
}
Upvotes: 13