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),
)
}
Related
On mobile, my modals cover the whole screen. They look exactly like whole new web pages. This leads to users getting confused. They expect to be able to press the back button and have the modal close. Instead the back button takes them back what they perceive as two steps.
I'm a novice at coding, so Javascript is all I've used for this, and even saying that feels like overselling my ability. I'm hoping you guys can help me figure this out.
Here's the code I used:
// Modals
// Modal Contact
function OpenModalContact () {
document.getElementById("Modal-Contact").style.display = "block";
}
// Modal-1 to 20
{
var modal1 = document.getElementById('Modal-01');
var modal2 = document.getElementById('Modal-02');
var modal3 = document.getElementById('Modal-03');
var modal4 = document.getElementById('Modal-04');
var modal5 = document.getElementById('Modal-05');
var modal6 = document.getElementById('Modal-06');
var modal7 = document.getElementById('Modal-07');
var modal8 = document.getElementById('Modal-08');
var modal9 = document.getElementById('Modal-09');
var modal10 = document.getElementById('Modal-10');
var modal11 = document.getElementById('Modal-11');
var modal12 = document.getElementById('Modal-12');
var modal13 = document.getElementById('Modal-13');
var modal14 = document.getElementById('Modal-14');
var modal15 = document.getElementById('Modal-15');
var modal16 = document.getElementById('Modal-16');
var modal17 = document.getElementById('Modal-17');
var modal18 = document.getElementById('Modal-18');
var modal19 = document.getElementById('Modal-19');
var modal20 = document.getElementById('Modal-20');
var modalContact = document.getElementById('Modal-Contact');
// Get the button that opens the modal
var Modalbtn01 = document.getElementById("ModalBtn01");
var Modalbtn02 = document.getElementById("ModalBtn02");
var Modalbtn03 = document.getElementById("ModalBtn03");
var Modalbtn04 = document.getElementById("ModalBtn04");
var Modalbtn05 = document.getElementById("ModalBtn05");
var Modalbtn06 = document.getElementById("ModalBtn06");
var Modalbtn07 = document.getElementById("ModalBtn07");
var Modalbtn08 = document.getElementById("ModalBtn08");
var Modalbtn09 = document.getElementById("ModalBtn09");
var Modalbtn10 = document.getElementById("ModalBtn10");
var Modalbtn11 = document.getElementById("ModalBtn11");
var Modalbtn12 = document.getElementById("ModalBtn12");
var Modalbtn13 = document.getElementById("ModalBtn13");
var Modalbtn14 = document.getElementById("ModalBtn14");
var Modalbtn15 = document.getElementById("ModalBtn15");
var Modalbtn16 = document.getElementById("ModalBtn16");
var Modalbtn17 = document.getElementById("ModalBtn17");
var Modalbtn18 = document.getElementById("ModalBtn18");
var Modalbtn19 = document.getElementById("ModalBtn19");
var Modalbtn20 = document.getElementById("ModalBtn20");
// Get the <span> element that closes the modal
var span1 = document.getElementById("CloseModal-01");
var span2 = document.getElementById("CloseModal-02");
var span3 = document.getElementById("CloseModal-03");
var span4 = document.getElementById("CloseModal-04");
var span5 = document.getElementById("CloseModal-05");
var span6 = document.getElementById("CloseModal-06");
var span7 = document.getElementById("CloseModal-07");
var span8 = document.getElementById("CloseModal-08");
var span9 = document.getElementById("CloseModal-09");
var span10 = document.getElementById("CloseModal-10");
var span11 = document.getElementById("CloseModal-11");
var span12 = document.getElementById("CloseModal-12");
var span13 = document.getElementById("CloseModal-13");
var span14 = document.getElementById("CloseModal-14");
var span15 = document.getElementById("CloseModal-15");
var span16 = document.getElementById("CloseModal-16");
var span17 = document.getElementById("CloseModal-17");
var span18 = document.getElementById("CloseModal-18");
var span19 = document.getElementById("CloseModal-19");
var span20 = document.getElementById("CloseModal-20");
var spanContact = document.getElementById("CloseModalContact");
// When the user clicks on the button, open the modal
ModalBtn01.onclick = function() {
modal1.style.display = "block";
}
ModalBtn02.onclick = function() {
modal2.style.display = "block";
}
ModalBtn03.onclick = function() {
modal3.style.display = "block";
}
ModalBtn04.onclick = function() {
modal4.style.display = "block";
}
ModalBtn05.onclick = function() {
modal5.style.display = "block";
}
ModalBtn06.onclick = function() {
modal6.style.display = "block";
}
ModalBtn07.onclick = function() {
modal7.style.display = "block";
}
ModalBtn08.onclick = function() {
modal8.style.display = "block";
}
ModalBtn09.onclick = function() {
modal9.style.display = "block";
}
ModalBtn10.onclick = function() {
modal10.style.display = "block";
}
ModalBtn11.onclick = function() {
modal11.style.display = "block";
}
ModalBtn12.onclick = function() {
modal12.style.display = "block";
}
ModalBtn13.onclick = function() {
modal13.style.display = "block";
}
ModalBtn14.onclick = function() {
modal14.style.display = "block";
}
ModalBtn15.onclick = function() {
modal15.style.display = "block";
}
ModalBtn16.onclick = function() {
modal16.style.display = "block";
}
ModalBtn17.onclick = function() {
modal17.style.display = "block";
}
ModalBtn18.onclick = function() {
modal18.style.display = "block";
}
ModalBtn19.onclick = function() {
modal19.style.display = "block";
}
ModalBtn20.onclick = function() {
modal20.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
spanContact.onclick = function() {
modalContact.style.display = "none";
}
span1.onclick = function() {
modal1.style.display = "none";
}
span2.onclick = function() {
modal2.style.display = "none";
}
span3.onclick = function() {
modal3.style.display = "none";
}
span4.onclick = function() {
modal4.style.display = "none";
}
span5.onclick = function() {
modal5.style.display = "none";
}
span6.onclick = function() {
modal6.style.display = "none";
}
span7.onclick = function() {
modal7.style.display = "none";
}
span8.onclick = function() {
modal8.style.display = "none";
}
span9.onclick = function() {
modal9.style.display = "none";
}
span10.onclick = function() {
modal10.style.display = "none";
}
span11.onclick = function() {
modal11.style.display = "none";
}
span12.onclick = function() {
modal12.style.display = "none";
}
span13.onclick = function() {
modal13.style.display = "none";
}
span14.onclick = function() {
modal14.style.display = "none";
}
span15.onclick = function() {
modal15.style.display = "none";
}
span16.onclick = function() {
modal16.style.display = "none";
}
span17.onclick = function() {
modal17.style.display = "none";
}
span18.onclick = function() {
modal18.style.display = "none";
}
span19.onclick = function() {
modal19.style.display = "none";
}
span20.onclick = function() {
modal20.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalContact) {
modalContact.style.display = "none";
}
if (event.target == modal1) {
modal1.style.display = "none";
}
if (event.target == modal2) {
modal2.style.display = "none";
}
if (event.target == modal3) {
modal3.style.display = "none";
}
if (event.target == modal4) {
modal4.style.display = "none";
}
if (event.target == modal5) {
modal5.style.display = "none";
}
if (event.target == modal6) {
modal6.style.display = "none";
}
if (event.target == modal7) {
modal7.style.display = "none";
}
if (event.target == modal8) {
modal8.style.display = "none";
}
if (event.target == modal9) {
modal9.style.display = "none";
}
if (event.target == modal10) {
modal10.style.display = "none";
}
if (event.target == modal11) {
modal11.style.display = "none";
}
if (event.target == modal12) {
modal12.style.display = "none";
}
if (event.target == modal13) {
modal13.style.display = "none";
}
if (event.target == modal14) {
modal14.style.display = "none";
}
if (event.target == modal15) {
modal15.style.display = "none";
}
if (event.target == modal16) {
modal16.style.display = "none";
}
if (event.target == modal17) {
modal17.style.display = "none";
}
if (event.target == modal18) {
modal18.style.display = "none";
}
if (event.target == modal19) {
modal19.style.display = "none";
}
if (event.target == modal20) {
modal20.style.display = "none";
}
}
}
// Close modal on ESC key press
document.addEventListener("keydown", function(event) {
if (event.keyCode === 27 &&
(document.querySelector("#Modal-Contact").style.display === "block" ||
document.querySelector("#Modal-01").style.display === "block" ||
document.querySelector("#Modal-02").style.display === "block" ||
document.querySelector("#Modal-03").style.display === "block" ||
document.querySelector("#Modal-04").style.display === "block" ||
document.querySelector("#Modal-05").style.display === "block" ||
document.querySelector("#Modal-06").style.display === "block" ||
document.querySelector("#Modal-07").style.display === "block" ||
document.querySelector("#Modal-08").style.display === "block" ||
document.querySelector("#Modal-09").style.display === "block" ||
document.querySelector("#Modal-10").style.display === "block" ||
document.querySelector("#Modal-11").style.display === "block" ||
document.querySelector("#Modal-12").style.display === "block" ||
document.querySelector("#Modal-13").style.display === "block" ||
document.querySelector("#Modal-14").style.display === "block" ||
document.querySelector("#Modal-15").style.display === "block" ||
document.querySelector("#Modal-16").style.display === "block" ||
document.querySelector("#Modal-17").style.display === "block" ||
document.querySelector("#Modal-18").style.display === "block" ||
document.querySelector("#Modal-19").style.display === "block" ||
document.querySelector("#Modal-20").style.display === "block" ))
{
document.querySelector("#Modal-Contact").style.display = "none";
document.querySelector("#Modal-01").style.display = "none";
document.querySelector("#Modal-02").style.display = "none";
document.querySelector("#Modal-03").style.display = "none";
document.querySelector("#Modal-04").style.display = "none";
document.querySelector("#Modal-05").style.display = "none";
document.querySelector("#Modal-06").style.display = "none";
document.querySelector("#Modal-07").style.display = "none";
document.querySelector("#Modal-08").style.display = "none";
document.querySelector("#Modal-09").style.display = "none";
document.querySelector("#Modal-10").style.display = "none";
document.querySelector("#Modal-11").style.display = "none";
document.querySelector("#Modal-12").style.display = "none";
document.querySelector("#Modal-13").style.display = "none";
document.querySelector("#Modal-14").style.display = "none";
document.querySelector("#Modal-15").style.display = "none";
document.querySelector("#Modal-16").style.display = "none";
document.querySelector("#Modal-17").style.display = "none";
document.querySelector("#Modal-18").style.display = "none";
document.querySelector("#Modal-19").style.display = "none";
document.querySelector("#Modal-20").style.display = "none";
}
});
// Close modal on back button for mobile
document.addEventListener("backbutton", function(event) {
if
(document.querySelector("#Modal-Contact").style.display === "block" ||
document.querySelector("#Modal-01").style.display === "block" ||
document.querySelector("#Modal-02").style.display === "block" ||
document.querySelector("#Modal-03").style.display === "block" ||
document.querySelector("#Modal-04").style.display === "block" ||
document.querySelector("#Modal-05").style.display === "block" ||
document.querySelector("#Modal-06").style.display === "block" ||
document.querySelector("#Modal-07").style.display === "block" ||
document.querySelector("#Modal-08").style.display === "block" ||
document.querySelector("#Modal-09").style.display === "block" ||
document.querySelector("#Modal-10").style.display === "block" ||
document.querySelector("#Modal-11").style.display === "block" ||
document.querySelector("#Modal-12").style.display === "block" ||
document.querySelector("#Modal-13").style.display === "block" ||
document.querySelector("#Modal-14").style.display === "block" ||
document.querySelector("#Modal-15").style.display === "block" ||
document.querySelector("#Modal-16").style.display === "block" ||
document.querySelector("#Modal-17").style.display === "block" ||
document.querySelector("#Modal-18").style.display === "block" ||
document.querySelector("#Modal-19").style.display === "block" ||
document.querySelector("#Modal-20").style.display === "block" )
{
document.querySelector("#Modal-Contact").style.display = "none";
document.querySelector("#Modal-01").style.display = "none";
document.querySelector("#Modal-02").style.display = "none";
document.querySelector("#Modal-03").style.display = "none";
document.querySelector("#Modal-04").style.display = "none";
document.querySelector("#Modal-05").style.display = "none";
document.querySelector("#Modal-06").style.display = "none";
document.querySelector("#Modal-07").style.display = "none";
document.querySelector("#Modal-08").style.display = "none";
document.querySelector("#Modal-09").style.display = "none";
document.querySelector("#Modal-10").style.display = "none";
document.querySelector("#Modal-11").style.display = "none";
document.querySelector("#Modal-12").style.display = "none";
document.querySelector("#Modal-13").style.display = "none";
document.querySelector("#Modal-14").style.display = "none";
document.querySelector("#Modal-15").style.display = "none";
document.querySelector("#Modal-16").style.display = "none";
document.querySelector("#Modal-17").style.display = "none";
document.querySelector("#Modal-18").style.display = "none";
document.querySelector("#Modal-19").style.display = "none";
document.querySelector("#Modal-20").style.display = "none";
event.preventDefault();
}
});
I've incorporated this, event.preventDefault(); but it doesn't seem to work
I hoped it would prevent the back button from doing it's default behaviour.
I've seen a post on here about something like this:
https://stackoverflow.com/a/49954532/18237477
But I'm unable to incorporate that solution into my code. Their code probably works but I don't understand it. I don't know how to merge that code into mine.
Core Data is crashing when doing a fetch request but I can't understand why. The error is suggesting EXC_BAD_ACCESS but it doesn't always occur for this particular fetch request. Basically when I zoom in and out on the mapView (MKMapKit), it's at that point it crashes.
For my mapView I use the following code:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let userStatus = CoreDataUserLocationManagement().returnUsersLastKnownStatus()
if (annotation is MKUserLocation) && userStatus != 3 {
As you can see from the above, this is when I request the lastKnownStatus, but as mentioned it doesn't always crash.
This fetch crashes here
func returnUsersLastKnownStatus() -> Int16 {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UsersLocationDetails")
do {
if let fetchResults = try managedObjectContext.fetch(fetchRequest) as? [UsersLocationDetails] {
if fetchResults.count != 0 {
let managedObject = fetchResults[0]
return managedObject.lastKnownStatus
}
}
}
catch {
print("Catch error retrieving last known status to Core Data")
}
return 3
}
The log is:
Printing description of fetchRequest:
(NSFetchRequest) fetchRequest = 0x0000000283a5be20 {
baseNSPersistentStoreRequest#0 = {
baseNSObject#0 = {
isa = NSFetchRequest
}
_affectedStores = 0x0000000000000000
}
_groupByProperties = 0x0000000000000000
_havingPredicate = 0x0000000000000000
_additionalPrivateIvars = 0x0000000281044100
_valuesToFetch = 0x0000000000000000
_entity = 0x0000000282684dc0 {
baseNSObject#0 = {
isa = NSEntityDescription
}
_cd_rc = 12
_snapshotClass = 0x000000028208a760
_versionHashModifier = 0x0000000000000000
_versionHash = some {
some = 0x0000000102faea90 {
baseNSData#0 = {
baseNSObject#0 = {
isa = _PFEncodedData
}
}
_aData = some {
some = 0x00000002811c7e60 {
baseNSData#0 = {
baseNSObject#0 = {
isa = _PFVMData
}
}
_cd_rc = 1732
_length = 40944
_payload = 0x0000000102fac000
}
}
_byteCount = 32
_reserved = 0
}
}
_model = some {
some = 0x00000002832a9400 {
baseNSObject#0 = {
isa = NSManagedObjectModel
}
_dataForOptimization = some {
some = 0x00000002811c7e60 {...}
}
_optimizationHints = 0x0000000102fb5850
_additionalPrivateIvars = 0x00000002811c0120
_entities = some {
some = 0x000000028239f9f0 {
baseNSKnownKeysDictionary1#0 = {
baseNSKnownKeysDictionary#0 = {
baseNSMutableDictionary#0 = {
NSDictionary = {
NSObject = {
isa = NSKnownKeysDictionary2
}
}
}
}
_cd_rc = 0
_count = 14
_keySearch = some {
some = 0x0000000102faeb10 {
baseNSKnownKeysMappingStrategy1#0 = {
baseNSKnownKeysMappingStrategy#0 = {
baseNSObject#0 = {
isa = NSKnownKeysMappingStrategy2
}
}
_cd_rc = -2128839072
_reserved64 = 2
_table = 0x0000000102faeb40
_length = 14
_reserved1 = 0x0000000000000000
_keys = 0x0000000102faec28
}
}
}
_values = {}
}
}
}
_configurations = 0x00000002811c0100 1 key/value pair
_fetchRequestTemplates = 0x0000000000000000
_versionIdentifiers = 0x00000002811c0140 1 element
}
}
_classNameForEntity = some {
some = 0x0000000102fad388 {
base_PFAbstractString#0 = {
baseNSString#0 = {
baseNSObject#0 = {
isa = _PFEncodedString
}
}
}
_cd_rc = 0
_length = 20
_sourceData = some {
some = 0x00000002811c7e60 {...}
}
}
}
_instanceClass = 0x00000002835b9b70
_name = some {
some = 0x0000000102fad388 {...}
}
_rootentity = 0x0000000282684dc0 {...}
_superentity = 0x0000000000000000
_subentities = 0x0000000000000000
_properties = some {
some = 0x00000002835b8720 {
baseNSKnownKeysDictionary1#0 = {
baseNSKnownKeysDictionary#0 = {
baseNSMutableDictionary#0 = {
NSDictionary = {
NSObject = {
isa = NSKnownKeysDictionary2
}
}
}
}
_cd_rc = 0
_count = 9
_keySearch = some {
some = 0x0000000102fb0bf0 {
baseNSKnownKeysMappingStrategy1#0 = {
baseNSKnownKeysMappingStrategy#0 = {
baseNSObject#0 = {
isa = NSKnownKeysMappingStrategy2
}
}
_cd_rc = -2128839072
_reserved64 = 2
_table = 0x0000000102fb0c20
_length = 9
_reserved1 = 0x0000000000000000
_keys = 0x0000000102fb0cd0
}
}
}
_values = {}
}
}
}
_propertyMapping = some {
some = 0x0000000102fb0bf0 {...}
}
_userInfo = 0x0000000000000000
_flattenedSubentities = 0x0000000281ff60d0 1 element
_kvcPropertyAccessors = 0x00000002832a92c0
_modelsReferenceIDForEntity = 13
}
_predicate = 0x0000000000000000
_sortDescriptors = 0x0000000000000000
_batchSize = 0
_fetchLimit = 0
_allocationSize = 0
_relationshipKeyPathsForPrefetching = 0x0000000000000000
}
Also just noticed this in Xcode:
(NSPersistentStoreRequest) CoreData.NSPersistentStoreRequest = <parent failed to evaluate: invalid load address>
So it turns out that it was this piece of code that code that was causing the issue. I have no idea why as the crash wasn't reporting this but as soon as I commented it out, it no longer crashes.
#IBAction func centerUserBtnTapped(_ sender: Any) {
let location = CLLocationCoordinate2D(latitude: locationManager.location?.coordinate.latitude ?? 0.0, longitude: locationManager.location?.coordinate.longitude ?? 0.0)
let span = MKCoordinateSpan.init(latitudeDelta: self.mapView.region.span.latitudeDelta, longitudeDelta: self.mapView.region.span.longitudeDelta)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
self.mapView.setUserTrackingMode(.follow, animated: true)
}
Instead I simplified it to the normal approach:
#IBAction func centerUserBtnTapped(_ sender: Any) {
mapView.setUserTrackingMode(.follow, animated: true)
}
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
}
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")
}
I'm building a today extension for iOS and I'm confused why this function keeps on using more and more memory.
See the code below:
func loadActivePlayer() {
kodi.getActivePlayer {
(response) in
let result = JSON(response)
let activePlayer = ActivePlayer()
if let playerid = result["result"][0]["playerid"].int {
activePlayer.playerid = playerid
}
if let type = result["result"][0]["type"].string {
activePlayer.type = type
}
if(activePlayer.isEmpty()) {
self.loadActivePlayer()
}
else {
self.enablePlaybackButtons(true)
self.activePlayer = activePlayer
self.kodi.getItem(activePlayer.playerid) {
(response) in
var result = JSON(response)
var item = Item()
if let id = result["result"]["item"]["id"].int {
item.id = id
}
if let type = result["result"]["item"]["type"].string {
item.type = type
}
if let label = result["result"]["item"]["label"].string {
item.label = label
}
if let title = result["result"]["item"]["title"].string {
item.title = title
}
if let season = result["result"]["item"]["season"].int {
item.season = season
}
if let episode = result["result"]["item"]["episode"].int {
item.episode = episode
}
if let showtitle = result["result"]["item"]["showtitle"].string {
item.showtitle = showtitle
}
dispatch_async(dispatch_get_main_queue()) {
self.itemTitleLabel.text = item.title
self.itemShowTitleLabel.text = item.showtitle
self.itemSeasonEpisodeLabel.text = "S\(item.season)E\(item.episode)"
}
self.loadActivePlayer()
}
}
}
When it goes in the if(activePlayer.isEmpty())
the memory usage increases and increases and increases, quite irritating.
But when it goes into the else, the memory usage stays almost the same, it does not increase significantly.
Can anyone help me understand why this is happening?
Thanx in advance!