Best way to count length of UITextInput text value in Swift? - swift

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.

For me personally the following code has worked fine in past.
if (!emailInput.text.isEmpty && !passwordInput.text.isEmpty) {
// enable button
} else {
// disable button
}

if((emailInput.text!.characters.count) > 0 && (passwordInput.text!.characters.count) > 0) {
// Enable button
} else {
// Disable button
}

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
}
}
}

Related

Is there a iOS standard for adding error messages to textFields?

I am trying to perform text validation on my textFields for user login and sign up and I want to display error text depending on what the user inputs. I have been trying to find if there is any sort of default implementation for displaying error text in or around a textfield that I can build off of but I have not been able to find anything. Is there a solution that doesn't involve relying upon external libraries?
I already have the logic for validating the textFields but I just need to display messages to the user. This is what I have:
#IBAction func signUpButton(_ sender: UIButton) {
if (emailTextField.text == "") {
print("Please enter an email.")
} else if (passwordTextField.text == "") {
print("Please enter a password.")
} else if (confirmPasswordTextField.text == "") {
print("Please confirm your password.")
} else if (confirmPasswordTextField.text != passwordTextField.text) {
print("Please ensure that your passwords are matching.")
} else if (!emailTextField.isEmail()) {
print("Please enter a valid email address.")
} else if (!passwordTextField.isValidPassword()) {
print("Passwords must be at least 8 characters in length and must contain at least one letter and one number.")
}
}
your can use UIAlertController to show the error messages.
For textField use
yourTextfield.text = "Error Message"
If you're looking for a built-in solution that is really low-effort like
inputView.validationErrorMessage = "you must enter an email"
then no, there is no such thing built in to UIKit. However there are many built-in mechanisms that can be very easily used to show error messages.
For example, UIAlertController can show a modal popup with possible options for them to choose from. Another approach is to add labels or imageviews that indicate a validation error and use the isHidden property to show/hide them at the appropriate time.

How to validate Text mesh pro input field text in unity

I have tried to use text mesh pro input field in my project but I have face one series issue with that. i.e If try to validate empty or null text in input field it fails. For example when user without typing any text in tmp input field and click done button I have set a validation like not allowed to save null empty values but when user click done button without typing any text, those validations are fails. Please suggest any idea to fix this issue. Thanks in advance.
Here is the code I have tried :
var text = TextMeshProText.text; // here "TextMeshProText" is 'TMP_Text'
if(!string.IsNullOrEmpty(text))
{
//do required functionality
}
else
{
// Show alert to the user.
}
I have set the validation like this but without giving any text click on done button it fails null or empty condition and enter in to if.
I found the problem. It fails because you use TMP_Text instead TMP_InputField.
Note that: Use the code for TMP_InputField; not for TMP_Text that is inside it as a child.
Change your code to this:
TMP_InputField TextMeshProText;
...
public void OnClick ()
{
var text = TextMeshProText.text; // here "TextMeshProText" is 'TMP_InputField'
if (!string.IsNullOrEmpty(text))
{
//do required functionality
}
else
{
// Show alert to the user.
}
}
I hope it helps you

Ace editor Detect if Change happen via Autocomplete

editor.getSession().on("change",function(editing){
if (ide.curOp && ide.curOp.command.name){
console.log("change when pressing keys");
}
else {
console.log("Changed when Click on autocomplete list or programically.");
// This change is programmatically but if its via click on autocomplete list or not?
// If its via click on autocomplete I want to save document else want to ignore.
}
});
My comment in code is explaining my question well.
The answer largely depends on what you call "programical", anything editor does is done via api calls so everything is "programical". E.g. if someone adds a <button onclick='editor.setValue("")'> will change caused by it be "programical" or not.
If you want to distinguish api calls made by your code from others, use a boolean variable and set it to true before calling into ace api, and to false after that.
var ignoreChanges = false
editor.session.on("change", function(delta){
if (ignoreChanges) return console.log("ignore changes made by me")
console.log("handle changes made in some other way")
})
function applyChange() {
try {
ignoreChanges = true
// call some editor api here
editor.insert("...")
} finally {
ignoreChanges = false
}
}

Swift - How can I add an event listener for cancelling an email dialog?

I'm using text attribute to detect an email. It's working fine but what I need is a listener if the user did cancel sending email or not.
How can I achieve that with Xcode?
Thanks a lot
You need to provide more information , photos of your problem.
And possible a sample code.
If you can detect a result of the email being added properly then you should handle the nil.
You didn't specify if the cancel option is a button or an .addAction method. In both cases you can use a Notification / Observers.
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
println("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
println("Added \(totalSteps - oldValue) steps")
}
}
}
}

How can I switch between UIReturnKeyGo and UIReturnKeyNext when text has been added to the UITextFields?

I'm trying to switch between the UIReturnKeyGo and the UIReturnKeyNext buttons depending on whether or not the user has entered some text in the fields or not, but it's not working the way I was hoping it would. Here's what I'm doing.
I created the following method:
- (void)setReturnKey {
if (self.isLoggingIn) {
if ([self.userField.text length] > 0 ||
[self.passField.text length] > 0) {
self.userField.returnKeyType = UIReturnKeyGo;
self.passField.returnKeyType = UIReturnKeyGo;
} else {
self.userField.returnKeyType = UIReturnKeyNext;
self.passField.returnKeyType = UIReturnKeyNext;
}
}
}
Then I added the above method to the textFieldDidBeginEditing delegate method, which will run anytime a field becomes active, and I created a textFieldDidChange method that is executed anytime text is entered or deleted. Unfortunately this is not working the way I hoped it would. The go button only appears when both fields are filled out and you actively click on another field, it doesn't update when you begin typing. So I can type in my username, then click next and start typing in my password, but the go button doesn't appear when I start entering my password, it will only show if I click the user field again.
Any idea what I'm doing wrong here or if there's a better way to accomplish this?
This is a bad idea. You'll just confuse the users. Keep the User field as Next and the Pass field as Go.