how to set func with boolean? - swift

I'm stuck validating textfields on the form screen. I don't want to allow requests to be thrown even if one of the textfields is empty. I want to show warning message for empty textfield. If all conditions are met, I would like to submit a request.
func isValid() -> Bool {
if nameTextField.text?.isEmpty == false {
nameWarningLabel.isHidden = true
nameTextField.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
}
else {
nameWarningLabel.isHidden = false
nameTextField.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
}
if surnameTextField.text?.isEmpty == false {
surnameWarningLabel.isHidden = true
surnameTextField.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
}
else {
surnameWarningLabel.isHidden = false
surnameTextField.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
}
if cellPhoneTextField.text?.isEmpty == false {
phoneWarningLabel.isHidden = true
cellPhoneTextField.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
}
else {
phoneWarningLabel.isHidden = false
cellPhoneTextField.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
}
if isChecked == true {
agreementCheckBoxButton.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
}
else {
agreementCheckBoxButton.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
}
if isChecked == true || (nameTextField.text?.count ?? 0) > 2 || (surnameTextField.text?.count ?? 0) > 2 || (cellPhoneTextField.text?.count ?? 0) < 10 {
return true
}
else {
return false
}
}
If this function returns true or false, I will send a request to the
service.
I am sharing the code block with you below

Create a BOOL variable within your function. Set the default value to true, and when it runs into an else condition, set it to false. Finally, at the end of your function, return the value of your BOOL variable. If all of the positive conditions are met, it will return the default value of true, otherwise return false.
func isValid() -> Bool {
//Declare Variable
var sendRequest:Bool = true
//Check Name Text Field
if nameTextField.text?.isEmpty == false {
nameWarningLabel.isHidden = true
nameTextField.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
} else {
nameWarningLabel.isHidden = false
nameTextField.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
sendRequest = false
}
//Check Surname Text Field
if surnameTextField.text?.isEmpty == false {
surnameWarningLabel.isHidden = true
surnameTextField.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
} else {
surnameWarningLabel.isHidden = false
surnameTextField.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
sendRequest = false
}
//Check Cell Phone Text Field
if cellPhoneTextField.text?.isEmpty == false {
phoneWarningLabel.isHidden = true
cellPhoneTextField.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
} else {
phoneWarningLabel.isHidden = false
cellPhoneTextField.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
sendRequest = false
}
//Check Agreement Check Box
if isChecked == true {
agreementCheckBoxButton.layer.borderColor = R.color.rgb_222_222_222()?.cgColor
} else {
agreementCheckBoxButton.layer.borderColor = R.color.rgb_249_36_23()?.cgColor
sendRequest = false
}
//Return Variable
return sendRequest
}

Related

Using Toggle in a password field in jetpack compose

I am trying to use toggle in a password field. This is my code so far but for some reason it wont work. How can I achieve toggling a password as in this image? Much appreciated!
Image: https://gyazo.com/5ad35b44dc955e0846c68f61ec9630b0
Column(
modifier = Modifier.padding(20.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
val username = remember { mutableStateOf(TextFieldValue()) }
val password = remember { mutableStateOf("") }
var revealPassword: MutableState<Boolean> =
remember { mutableStateOf(false) } // To reveal the password with toggle
Text(text = "Sign in", style = TextStyle(fontSize = 40.sp, fontFamily = FontFamily.Cursive))
Text(
text = "here",
style = TextStyle(fontSize = 40.sp, fontFamily = FontFamily.Cursive)
)
// PASSWORD
Spacer(modifier = Modifier.height(20.dp))
OutlinedTextField(
value = password.value,
onValueChange = { newText ->
password.value = newText
},
visualTransformation = if (revealPassword.value) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
},
trailingIcon = {
if (revealPassword.value) {
IconButton(onClick = {
(I changed this!! -->) revealPassword.Value = false
}) { Icon(imageVector = Icons.Filled.Visibility, contentDescription = null) }
} else {
IconButton(onClick = {
(I changed this!! -->) revealPassword.Value = true }) {
Icon(imageVector = Icons.Filled.VisibilityOff, contentDescription = null)
}
}
},
label = { Text(text = "Password") },
singleLine = true,
leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = null) },
modifier = Modifier
.fillMaxWidth(180F),
)
You have given revealPassword = true in both onClick().
Change the first one to revealPassword = false
Complete code
#Composable
fun TogglePassword() {
val password = remember {
mutableStateOf("")
}
var revealPassword: MutableState<Boolean> = remember {
mutableStateOf(false)
} // To reveal the password with toggle
OutlinedTextField(
value = password.value,
onValueChange = { newText ->
password.value = newText
},
visualTransformation = if (revealPassword.value) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
},
trailingIcon = {
if (revealPassword.value) {
IconButton(
onClick = {
revealPassword.value = false
},
) {
Icon(imageVector = Icons.Filled.Visibility, contentDescription = null)
}
} else {
IconButton(
onClick = {
revealPassword.value = true
},
) {
Icon(imageVector = Icons.Filled.VisibilityOff, contentDescription = null)
}
}
},
label = {
Text(text = "Password")
},
singleLine = true,
leadingIcon = {
Icon(imageVector = Icons.Default.Lock, contentDescription = null)
},
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
)
}
You are setting boolean wrong.
And I think it is cleaner to control VisualTransformation above.
#Composable
fun PasswordTextField() {
var masked by remember {
mutableStateOf(false)
}
var password by remember {
mutableStateOf("")
}
val visualTransformation by remember(masked) {
if (masked)
mutableStateOf(PasswordVisualTransformation())
else
mutableStateOf(VisualTransformation.None)
}
OutlinedTextField(
value = password,
onValueChange = { newText ->
password = newText
},
visualTransformation = visualTransformation,
trailingIcon = {
if (masked) {
IconButton(onClick = {
masked = false
}) { Icon(imageVector = Icons.Filled.VisibilityOff, contentDescription = null) }
} else {
IconButton(onClick = { masked = true }) {
Icon(imageVector = Icons.Filled.Visibility, contentDescription = null)
}
}
},
label = { Text(text = "Password") },
singleLine = true,
modifier = Modifier
.fillMaxWidth(.1f),
)
}

Set a global variable from within GeoCoder function Swift

I have a global variable "filterError" that is initially set to false before a switch statement. When the switch statement occurs, it will go through a dictionary, and for each key it will do a unique logic check on the value. If that value does not match certain criteria then the Boolean variable filterError will be set to true.
When the switch statement is complete, if filterErrror is false then the an action will occur like so:
//...switch statement...
if (filterErrror == false) {
//do something.....
}
The issue I am having is with the geocoder function which is a case in the switch statement. If the switch variable key = "area" then the below is executed:
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,let location = placemarks.first?.location
else { print("Error in finding location") return }
let distanceInMeters = location.distance(from: coordinateSelf)
print("The distance between property and user in miles is: \(distanceInMeters/1609)")
distanceInMiles = distanceInMeters/1609
var radius = Double()
if searchRadius == "this area only" {
radius = 0.49999999999
} else {
radius = Double(Int(searchRadius)!)
}
if (radius < distanceInMiles) {
filterError = true
}
}
However, the filterError is still false after the switch statement has completed because the boolean value is not being changed. How do you set filterError to true from inside the geocoder?
This is the full code:
for filter in self.activeFilters {
switch filter.key {
case "listingType":
if(filter.value[0] != propertiesFirestore[i]["listingType"]![0]){
filterError = true
}
case "minBedsBound":
if(filter.value[0] != "No min. beds") {
if(filter.value[0].filter("01234567890.".contains) > propertiesFirestore[i]["bedroomCount"]![0]) {
filterError = true
}
}
case "maxBedsBound":
if(filter.value[0] != "No max. beds") {
if(Int(filter.value[0].filter("01234567890.".contains))! < Int(propertiesFirestore[i]["bedroomCount"]![0])!) {
filterError = true
}
}
case "minPriceBound":
if(filter.value[0] != "No min. price") {
if(Int(filter.value[0].filter("01234567890.".contains))! > Int(propertiesFirestore[i]["price"]![0])!) {
filterError = true
}
}
case "maxPriceBound":
if(filter.value[0] != "No max. price") {
if(Int(filter.value[0].filter("01234567890.".contains))! < Int(propertiesFirestore[i]["price"]![0])!) {
filterError = true
}
}
case "includeSharedOwnership":
if(filter.value[0] != propertiesFirestore[i]["sharedOwnership"]![0]) {
filterError = true
}
case "includeRetirementHomes":
if(filter.value[0] != propertiesFirestore[i]["retirementHome"]![0]) {
filterError = true
}
case "area":
print(userlatitude)
print(userlongitude)
let address = "\(propertiesFirestore[i]["area"]![0]), \(propertiesFirestore[i]["postcodePrefix"]![0])"
var propLat = String()
var propLong = String()
var distanceInMiles = Double()
var searchRadius = self.activeFilters["searchRadius"]![0]
let coordinateSelf = CLLocation(latitude: Double(userlatitude) as! CLLocationDegrees, longitude: Double(userlongitude) as! CLLocationDegrees)
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard
let placemarks = placemarks,
let location = placemarks.first?.location
else {
print("Error in finding location")
return
}
let distanceInMeters = location.distance(from: coordinateSelf)
print("The distance between property and user in miles is: \(distanceInMeters/1609)")
distanceInMiles = distanceInMeters/1609
var radius = Double()
if searchRadius == "this area only" {
radius = 0.49999999999
} else {
radius = Double(Int(searchRadius)!)
}
if (radius < distanceInMiles) {
filterError = true
}
}
case "keywords":
print("Filter keywords are: \(filter.value)")
for j in 0..<propertiesFirestore[i]["keywords"]!.count {
propertiesFirestore[i]["keywords"]![j] = propertiesFirestore[i]["keywords"]![j].lowercased()
}
for keyword in filter.value {
if propertiesFirestore[i]["keywords"] == nil {
filterError = true
} else if ((propertiesFirestore[i]["keywords"]!.contains(keyword.lowercased()))) {
print("found keyword")
} else {
filterError = true
}
}
default:
print("Unknown filter: \(filter.key)")
}
}
if filterError == false {
filterProperties.append(propertiesFirestore[i])
} else {
print("FITLER CATCHOUT")
}

Confusion about setting a optional variable

I want to add the option for a user to add their phone number. If they add any phone number I want to add an alert informing them if they have not added a valid 10 digit phone number. However if they do not add anything in the phone number field I want the phoneInput variable to be set to "0". How would I go about doing this.
var phoneInput = ""
func signUp(){
if profileImage.image == nil {
showAvatarError()
} else if phoneNumber.text == "" {
self.phoneInput = "0"
} else if (phoneNumber.text?.characters.count)! != 10 {
showphoneNumberError()
}else if email.text == "" {
showEmailError()
}else if isValid(email.text!) != true{
showEmailError()
} else{
submitPressed()
print("Set info")
}
}
I'm not sure why you get the result that you do but here is a cleaner version
var phoneInput = ""
func signUp(){
// This check doesn't have anything to do with the number, so separe it
if profileImage.image == nil {
showAvatarError()
return
}
guard let temp = planEndValue.text else {
return
}
let userInput = temp.trimmingCharacters(in: .whitespaces)
if userInput.count == 0 {
self.phoneInput = "0"
} else if userInput.count != 10 {
showphoneNumberError()
}
}

Checking the String whether it is the Number(Double) of

Question. It is necessary to make check the String whether it is the Number(Double)?
Exemple:
var s1:String = "df1231"
var s2:String = "1231,3123"
If s1.isDouble {
Println("True.This Number!")
} else {
Println("False.This not Number!") //Will give it
}
If s2.isDouble {
Println("True.This Number!") //Will give it
} else {
Println("False.This not Number!")
}
Not sure what your needs are exactly, but the most straightforward way to do it could be:
func isDouble(text:String) -> Bool {
guard let _ = Double(text.stringByReplacingOccurrencesOfString(",", withString: ".")) else { return false }
return true
}
isDouble("df1231") // returns false
isDouble("1231,3123") // returns true
You can copy paste it to Playground to see it work.

How to check dictionary value is empty or not

i am new to swift and facing little issue and i not understanding how to check dictionary value.
func doValidate(data:Dictionary<String,AnyObject>,isEmail : String) -> Bool {
if(isEmail=="signup"){
if( data["last_name"] == nil || data["email"] == nil || data["password"] == nil || data["first_name"] == nil){
return false;
}
else{
return true;
}
}
}
Dictionary key is always constant and every time dictionary key exists but how i can check
value of data["last_name"] is empty or not?
if i used loop then its working but why single value not work?
for( myKey,myValue ) in data {
if(myValue as! String == ""){ // Work Perfect
return false;
}
}
For checking the value use objectForKey()
Here is modified code
func doValidate(data:Dictionary<String,AnyObject>,isEmail : String) -> Bool {
if(isEmail=="signup"){
if( data.objectForKey("last_name") == nil || data.objectForKey("email") == nil || data.objectForKey("password") == nil || data.objectForKey("first_name") == nil){
return false;
}
else{
return true;
}
}
}
You could consider the syntax introduced with Swift 1.2 inverting your if logic, obtaining something like this:
func doValidate(data:Dictionary<String,AnyObject>,isEmail : String) -> Bool {
if(isEmail == "signup"){
if let lastName = data["last_name"] as? String,
let email = data["email"] as? String,
let password = data["password"] as? String,
let firstName = data["first_name"] as? String
where
!lastName.isEmpty &&
!email.isEmpty &&
!password.isEmpty &&
!firstName.isEmpty {
return true
}
}
return false
}
Check length if you wanna check your string value. for example
func doValidate(data:Dictionary<String,AnyObject>,isEmail : String) -> Bool {
if(isEmail=="signup"){
if( data["last_name"]?.length == 0 || data["email"]?.length == 0 || data["password"]?.length == 0 || data["first_name"]?.length == 0){
return false;
}
else{
return true;
}
}
}