iOS: Setting variables on several custom view objects - ios

Okay, so I'm creating X number of a custom UIView, that I've created in IB...
I create them in a grid-like formation and need to set their individual properties based on a response from a web service call...
The part I'm having trouble with is how to iterate through the different UIViews and set the variables...
I'm pretty sure the solution is really simple, but I've been staring blindly at this for some time now...
It's the part after:
if([theStatus.groupName isEqualToString:groupEntry.groupNameLabel.text])
{
Here is the entire method:
- (void)receivedGroups
{
int rows, columns;
if([groupConnection.groupsArray count] <= 4)
{
rows = 1;
columns = [groupConnection.groupsArray count];
} else if([groupConnection.groupsArray count] >= 5 && [groupConnection.groupsArray count] <= 8)
{
rows = 2;
columns = ([groupConnection.groupsArray count] + 1 )/ 2;
} else
{
rows = 3;
columns = ([groupConnection.groupsArray count] + 2 )/ 3;
}
int number = 0;
for(int j=1; j < columns+1; j++)
{
for(int k=0; k < rows; k++)
{
// Only create the number of groups that match the number of entries in our array
if(number < [groupConnection.groupsArray count])
{
// Create an instance of the group view
GroupEntry *groupEntry = [[GroupEntry alloc] initWithFrame:CGRectMake(230*j, 250*k, 180, 233)];
// Add it to the view
[self.view addSubview:groupEntry];
// Get the group
GetGroupsActive *theGroups = [groupConnection.groupsArray objectAtIndex:number];
groupEntry.groupNameLabel.text = theGroups.groupName;
for(int i=0; i<[statusConnection.statusArray count]; i++)
{
CurrentStatus *theStatus = [statusConnection.statusArray objectAtIndex:i];
if([theStatus.groupName isEqualToString:groupEntry.groupNameLabel.text])
{
//allChildren++;
switch(theStatus.currentStatus)
{
case 0:
//childrenSick++;
break;
case 1:
//childrenVacation++;
break;
case 2:
//childrenPresent++;
break;
case 3:
//childrenOut++;
break;
case 4:
//childrenTour++;
break;
default:
break;
}
}
}
NSString *allLabelText = [NSString stringWithFormat:#"%i", allChildren];
NSString *sickLabelText = [NSString stringWithFormat:#"%i", childrenSick];
NSString *vacationLabelText = [NSString stringWithFormat:#"%i", childrenVacation];
NSString *presentLabelText = [NSString stringWithFormat:#"%i", childrenPresent];
NSString *outLabelText = [NSString stringWithFormat:#"%i", childrenOut];
NSString *tripLabelText = [NSString stringWithFormat:#"%i", childrenTour];
groupEntry.sickLabelNumber.text = sickLabelText;
groupEntry.presentLabelNumber.text = presentLabelText;
groupEntry.numberLabelNumber.text = allLabelText;
groupEntry.tripLabelNumber.text = tripLabelText;
groupEntry.outLabelNumber.text = outLabelText;
groupEntry.vacationLabelNumber.text = vacationLabelText;
// Create the buttons to handle button press
UIButton *childButton = [UIButton buttonWithType:UIButtonTypeCustom];
childButton.frame = CGRectMake(230*j, 250*k, 180, 233);
// Set an identity tag, so we can recognize it during button press
childButton.tag = theGroups.ID;
// When EventTouchUpInside, send an action to groupSelected:
[childButton addTarget:self action:#selector(groupSelected:) forControlEvents:UIControlEventTouchUpInside];
// Add it to the view
[self.view addSubview:childButton];
}
number++;
}
}
}

If you added all the views in a parent view. You can get all the subviews using,
NSAarry *subviews = [base subviews];
for(UIView *subview in subviews)
{
subview.property = yourVaule;
}
You can differentiate between subviews using its tag or another property.

Related

How to remove data from an array comparing using string not an index in objective-C

I have an array of dictionary like below
self->arrField: (
{
fieldname = "Have you ever had any one of the following:";
fieldvalue = (
Diabetes,
Hypertension
);
tagvalue = 0;
},
{
fieldname = "By continuing with this survey, you agree to our terms of use and Parsons Information Governance and Privacy Policies, Procedures and Standards, available on the Corporate Policy Center.";
fieldvalue = Agree;
tagvalue = 1;
},
{
fieldname = "Have you tested positive for COVID-19 in the last 10 days?";
fieldvalue = No;
tagvalue = 4;
},
{
fieldname = "Do you have any known heart conditions or on any medications that elevate your heart rate";
fieldvalue = Yes;
tagvalue = 6;
},
{
fieldname = "Have you received a COVID-19 test in the past 48 hours";
fieldvalue = Yes;
tagvalue = 7;
},
{
fieldname = "In the last 48 hours have you experienced any of these symptoms";
fieldvalue = (
cough,
fever
);
tagvalue = 10;
}
)
So if the user changes any of the fieldvalue I need to replace that array, I have tried using replaceObjectAtIndex but it will not work out because I need compare the string.
Below is my implementation:
-(void)ChkUnChk:(UIButton*)sender {
dispatch_async(dispatch_get_main_queue(), ^{
UIButton *btn=(UIButton *)sender;
NSString *strValue = btn.accessibilityHint;
NSString *Str=[NSString stringWithFormat:#"%d",(int)btn.tag];
int iTag = [[sender.layer valueForKey:#"anyKey"] intValue];
// new Implementation
NSMutableDictionary *dictFields = [[NSMutableDictionary alloc] init];
NSMutableArray *arrFieldvalue = [[NSMutableArray alloc] init];
[dictFields setObject:[[self->dictCustomFieldGroups valueForKey:#"name"] objectAtIndex:iTag] forKey:#"fieldname"];
[dictFields setObject:[NSString stringWithFormat:#"%ld",(long)iTag] forKey:#"tagvalue"];
if ([self isTagIDAvailable:iTag]) {
arrFieldvalue = [[[self->arrTempCheckboxFields objectAtIndex:self->checkboxIndex] valueForKey:#"fieldvalue"] mutableCopy];
BOOL isTheObjectThere = [arrFieldvalue containsObject: strValue];
if (isTheObjectThere) {
NSLog(#"string contains");
[btn setBackgroundImage:[UIImage systemImageNamed:#"square"] forState:UIControlStateNormal];
for(id item in arrFieldvalue) {
if([item isEqual:strValue]) {
[arrFieldvalue removeObject:item];
[dictFields setObject:arrFieldvalue forKey:#"fieldvalue"];
break;
}
}
} else {
NSLog(#"string does not contain!");
[btn setBackgroundImage:[UIImage systemImageNamed:#"checkmark.square"] forState:UIControlStateNormal];
[arrFieldvalue addObject:strValue];
[dictFields setObject:arrFieldvalue forKey:#"fieldvalue"];
}
NSInteger count = [self->arrFields count];
for (NSInteger index = (count - 1); index >= 0; index--) {
NSArray *p = self->arrFields[index];
if ([[self->arrFields valueForKey:#"tagvalue"] isEqual:[NSNumber numberWithInt:iTag]]) {
[self->arrFields removeObjectAtIndex:index];
}
}
[self->arrFields replaceObjectAtIndex:iTag withObject:dictFields];
[self->arrTempCheckboxFields replaceObjectAtIndex:self->checkboxIndex withObject:dictFields];
} else {
[btn setBackgroundImage:[UIImage systemImageNamed:#"checkmark.square"] forState:UIControlStateNormal];
[arrFieldvalue addObject:strValue];
[dictFields setObject:arrFieldvalue forKey:#"fieldvalue"];
[self->arrFields addObject:dictFields];
[self->arrTempCheckboxFields addObject:dictFields];
}
NSLog(#"self->arrField: %#",self->arrFields);
});
}
-(BOOL) isTagIDAvailable:(int)tagID {
BOOL retVal = FALSE;
BOOL tagIdFound = FALSE;
if ([arrTagID count] > 0) {
for (int i = 0; i < [arrTagID count]; i++) {
if ([[NSNumber numberWithInteger:tagID] isEqualToNumber:[arrTagID objectAtIndex:i]]) {
tagIdFound = TRUE;
checkboxIndex = i;
retVal = TRUE;
break;
}
}
if (!tagIdFound) {
[arrTagID addObject:[NSNumber numberWithInteger:tagID]];
checkboxIndex = (int)[arrTagID count];
retVal = FALSE;
}
} else {
[arrTagID addObject:[NSNumber numberWithInteger:tagID]];
retVal = FALSE;
}
return retVal;
}
I have done something from line no 32, like I will remove that array value and add it again.But I am not sure how to do that. If more detail require I can provide.
Thanks in Advance.

Executes same code more than once. How to use Goto statement inside for loop

I have code which is used more than two times in different condition in same function. So I decided to use Goto statement. But that code will be executed inside for loop. So I don't understand how to call same code in same function. I don't want to create one more function. My code is...
- (void)setSelectedSearchCriteria:(NSString *)storedValue storedTag:(NSString *)storedTag D_Key:(NSString *)D_Key D_Tag_Value:(NSString *)D_Tag_Value arrayMain:(NSMutableArray *)arrayMain bgView:(UIView *)bgView
{
//Add data
NSMutableArray *sArray = [[storedValue componentsSeparatedByString:#","] mutableCopy];
NSMutableArray *sTagArray = [[storedTag componentsSeparatedByString:#","] mutableCopy];
[sArray removeObject:#""];
[sTagArray removeObject:#""];
int maxTag = 0;
if (sTagArray.count != 0)
{
maxTag = [[sTagArray valueForKeyPath:#"#max.intValue"] intValue];
for (int i = maxTag + 1; i <= [D_Tag_Value intValue]; i++)
goto add_value;
}
else
goto add_value;
add_value:
{
NSString *D_Value = [[arrayMain objectAtIndex:[D_Tag_Value intValue]] valueForKey:PARAMETER_KEY];
if (![sArray containsObject:D_Value])
{
[sArray addObject:D_Value];
[sTagArray addObject:D_Tag_Value];
}
//Add data
UIButton *btn = (UIButton *)[bgView viewWithTag:[D_Tag_Value intValue]];
[self setSelectedButtonStyle:btn];
}
storedValue = [[[sArray valueForKey:KEY_DESCRIPTION] componentsJoinedByString:#","] mutableCopy];
storedTag = [[[sTagArray valueForKey:KEY_DESCRIPTION] componentsJoinedByString:#","] mutableCopy];
[SEARCH_CRITERIAS setValue:storedValue forKey:D_Key];
[SEARCH_CRITERIAS_TAG setValue:storedTag forKey:D_Key];
}
Code inside add_value executed in for loop and also in else part. So I don't know how to manage this.
Define a block inside your function
void(^theBlock)(void) = ^(){
NSString *D_Value = [[arrayMain objectAtIndex:[D_Tag_Value intValue]] valueForKey:PARAMETER_KEY];
if (![sArray containsObject:D_Value])
{
[sArray addObject:D_Value];
[sTagArray addObject:D_Tag_Value];
}
//Add data
UIButton *btn = (UIButton *)[bgView viewWithTag:[D_Tag_Value intValue]];
[self setSelectedButtonStyle:btn];
};
I don't fully understand what do you do in your add_value. If it can change to a block receive some parameters and return some value that would be better
after that you simply call the block
theBlock();
The code doesn't actually depend on the loop counter, so it isn't too hard to refactor the code so that you can simply execute the loop the appropriate number of times.
- (void)setSelectedSearchCriteria:(NSString *)storedValue storedTag:(NSString *)storedTag D_Key:(NSString *)D_Key D_Tag_Value:(NSString *)D_Tag_Value arrayMain:(NSMutableArray *)arrayMain bgView:(UIView *)bgView
{
//Add data
NSMutableArray *sArray = [[storedValue componentsSeparatedByString:#","] mutableCopy];
NSMutableArray *sTagArray = [[storedTag componentsSeparatedByString:#","] mutableCopy];
[sArray removeObject:#""];
[sTagArray removeObject:#""];
int loopCount = 1;
if (sTagArray.count != 0) {
int maxTag = [[sTagArray valueForKeyPath:#"#max.intValue"] intValue];
loopCount = [D_Tag_Value intValue] - maxTag;
}
for (int i = 0; i < loopCount ; i++) {
NSString *D_Value = [[arrayMain objectAtIndex:[D_Tag_Value intValue]] valueForKey:PARAMETER_KEY];
if (![sArray containsObject:D_Value])
{
[sArray addObject:D_Value];
[sTagArray addObject:D_Tag_Value];
}
//Add data
UIButton *btn = (UIButton *)[bgView viewWithTag:[D_Tag_Value intValue]];
[self setSelectedButtonStyle:btn];
}
storedValue = [[[sArray valueForKey:KEY_DESCRIPTION] componentsJoinedByString:#","] mutableCopy];
storedTag = [[[sTagArray valueForKey:KEY_DESCRIPTION] componentsJoinedByString:#","] mutableCopy];
[SEARCH_CRITERIAS setValue:storedValue forKey:D_Key];
[SEARCH_CRITERIAS_TAG setValue:storedTag forKey:D_Key];
}

Add effect for buttons

I have an app like Hangman, the difference is that in my app the letters chosen are in order, not on the right space .
-(void)MatchedWordClick:(id)sender{
UIButton *bt = (UIButton*)sender;
[bt setTitle:#"" forState:UIControlStateNormal];
((UIButton*)[PuzzleView viewWithTag:[[[lstWordToMatch objectAtIndex:nCurrentWord]objectAtIndex:bt.tag-200] integerValue]+100]).hidden = FALSE;
[[lstWordToMatch objectAtIndex:nCurrentWord]replaceObjectAtIndex:bt.tag-200 withObject:[NSString stringWithFormat:#"%d",-1]];
}
-(void)PuzzleWordClick:(id)sender{
//AudioServicesPlaySystemSound(sound1);
UIButton *bt = (UIButton*)sender;
int nIndex = -1;
for (int i = 0; i< [[lst_word objectAtIndex:nCurrentWord]length]; i++) {
UIButton *bt1 = (UIButton*)[self.view viewWithTag:200+i];
if ([bt1.currentTitle isEqualToString:#""]||bt1.currentTitle == nil) {
nIndex = i;
break;
}
}
if (nIndex == -1) {
NSLog(#"You Macthed Already");
}else{
bt.hidden = TRUE;
[[lstWordToMatch objectAtIndex:nCurrentWord]replaceObjectAtIndex:nIndex withObject:[NSString stringWithFormat:#"%d",bt.tag-100]];
[((UIButton*)[self.view viewWithTag:200+nIndex])setTitle:bt.titleLabel.text forState:UIControlStateNormal];
}
int nCount = 0;
for (int i = 0; i< [[lst_word objectAtIndex:nCurrentWord]length]; i++) {
UIButton *bt1 = (UIButton*)[self.view viewWithTag:200+i];
if ([bt1.currentTitle isEqualToString:#""]||bt1.currentTitle == nil) {
nCount++;
}
}
if (nCount == 0) {
NSString *strWord = #"";
for (int i = 0; i<[[lst_word objectAtIndex:nCurrentWord]length]; i++) {
UIButton *bt1 = (UIButton*)[self.view viewWithTag:200+i];
strWord = [NSString stringWithFormat:#"%#%#",strWord,bt1.currentTitle];
}
if (![strWord isEqualToString:[lst_word objectAtIndex:nCurrentWord]]) {
MatchView.userInteractionEnabled = FALSE;
PuzzleView.userInteractionEnabled = FALSE;
ErrorAlertView.hidden = FALSE;
// AudioServicesPlaySystemSound(sound3);
}else{
if (nCurrentWord == 0) {
//// Change Points Value
if ([[lst_word objectAtIndex:nCurrentWord] length] == 3) {
[lblPts setText:[NSString stringWithFormat:#"%d", nPoint+5]];//point value
}else if ([[lst_word objectAtIndex:nCurrentWord] length] == 4) {
[lblPts setText:[NSString stringWithFormat:#"%d", nPoint+10]];
}else if ([[lst_word objectAtIndex:nCurrentWord] length] >= 5) {
[lblPts setText:[NSString stringWithFormat:#"%d", nPoint+15]];
}
[self drawSuccessView];
}else{
nCurrentWord++;
[self drawPuzzle:nCurrentWord];
}
}
}
}
This code is working to select a letter and complete the word, it also works if I want to erase the letter and put it back .
I want that when I select a letter (from puzzle or from word) to add an effect like fly when a letter is put back or in the word.
I want something like this effect but I don't know how to do it in this case.
int z=40 + random() % 9;
int w=40+ random() % 9;
[UIView animateWithDuration:0.5 animations:^{
self.label13.frame = CGRectMake(-z,-200, 25, 25);
NSLog(#"aaa");
}];

Randomizing position of correct answer in a quiz application for ios(Objective -C)

I am trying to develop a simple quiz application for IOS. I need to pick up 10 random images out of 50 , and display each image and 4 options with one correct answer. Presently I am able to randomize images , but each time, the correct option is displayed only at one position. Can anyone help me for randomizing the position of correct answer for different questions (i.e, images)?
- (void)viewDidAppear:(BOOL)animated
{
myData = nil;
[super viewDidAppear:animated];
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"WoodTexture"]]];
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Images" ofType:#"plist"];
myData = [[NSMutableArray alloc] initWithContentsOfFile:bundle];
[self setImageswithOptions];
count = 0;
score = 0;
[self resetScreen];
}
The method definition goes below.
- (void)setImageswithOptions
{
NSInteger number[4],i;
for ( i = 0; i <4 ; ++i ) {
number[i] = arc4random() % myData.count ;
for (int j = 0; j < i; ++j) {
if ((number[i] < 0) || (number[i] == number[j] )) {
--i;
}
}
}
self.submit.hidden =YES;
self.displayImage.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#",myData[number[0]]]];
NSInteger random = arc4random() % 4;
if (random == 0) {
random += 1;
}
[(UILabel *)[self.view viewWithTag:random] setText:[NSString stringWithFormat:#"%#",myData[number[0]]]];
[(WQZOptionButton *)[self.view viewWithTag:random + 4] setIsCorrect:YES];
NSInteger imageCount = 0;
for (NSInteger index = 1; index <= 4; index++) {
if (index != random) {
imageCount++;
[(UILabel *)[self.view viewWithTag:index] setText:[NSString stringWithFormat:#"%#",myData[number[imageCount]]]];
[(WQZOptionButton *)[self.view viewWithTag:index + 4] setIsCorrect:NO];
}
}
[myData removeObjectAtIndex:number[0]];
self.scoreLabel.text = [NSString stringWithFormat:#"Score: %ld", (long)score];
}
There are several problems.
One problem:
NSInteger random = arc4random() % 4;
if (random == 0) {
random += 1;
}
random will be 1, 2 or 3 and 1 will occur twice as often as 2 or 3.
Also it is better to use arc4random_uniform() than the modular operator:
Instead of arc4random() % 4
use arc4random_uniform(4)

How to delete the number from non repeating number array?

I am trying this code for generating a random number and saving the list of numbers in an array, then i am trying to delete those numbers from the list one by one which appeared once, e.g
1, 5, 9 , 4, 3, 7 ,6 ,10, 11, 8, 2 are the list of integers now 9 is appeared once and now i do not need 9 again.. this is my code of random non repeating numbers array.
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
BOOL record = NO;
int x;
for (int i=0; [storeArray count] < 10; i++) //Loop for generate different random values
{
x = arc4random() % 10;//generating random number
if(i==0)//for first time
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
else
{
for (int j=0; j<= [storeArray count]-1; j++)
{
if (x ==[[storeArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
{
record = NO;
}
else
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
}
}
Try this,
NSArray *arrRandoms = [[NSArray alloc]initWithObjects:1,5,8,7,36,17,96,32,5,7,8,13,36,nil] ; // This contains your random numbers
NSMutableArray *arrFresh = [[NSMutableArray alloc]init];
// Now removing the duplicate numbers
BOOL checkRepeat = NO;
int _Current;
for (int i=0; i<[arrRandoms count]; i++)
{
_Current = [arrRandoms objectAtIndex:i];
if (i == 0)
[arrFresh addObjects:_Current];
else
{
checkRepeat = NO;
for(int j=0; j< [arrFresh count]; j++)
{
if ( _Current == [arrFresh objectAtIndex:j])
checkRepeat = YES;
}
if (checkRepeat == NO)
[arrFresh addObjects:_Current];
}
}
I think this code will work. Check It.
try it
//**************remove repeat objects from array***************************//
NSArray *noDuplicates = [[NSSet setWithArray: yourArray] allObjects];
you add
.h file
BOOL isSame;
NSMutableArray *countArray;
NSInteger randomNumber;
.m file
countArray=[[NSMutableArray alloc]init];
//get randon no
-(NSInteger)getRandomNo:(NSInteger)range
{
isSame=TRUE;
while (isSame){
isSame = FALSE;
randomNumber = arc4random() % range;
for (NSNumber *number in countArray){
if([number intValue] ==randomNumber){
isSame = TRUE;
break;
}
}
}
[countArray addObject:[NSNumber numberWithInt:randomNumber]];
return randomNumber;
}
Tested Please try this,
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
NSMutableSet * setUnique = [[NSMutableSet alloc] init];
for (int i=0; [setUnique count] < 10; i++) //Loop for generate different random values
{
[setUnique addObject:[NSNumber numberWithInt:arc4random() % 10]];
}
storeArray = [[setUnique allObjects] mutableCopy];
// check this how to get random number in array (i.e.. this array(below arr_numbers) contain non repeated number)
// for general purpose i am posting this.. so people cannot check for another answer
int num_count = 10;
int RandomNumber;
NSMutableArray *arr_numbers = [[NSMutableArray alloc] init];
for (int j =0; j < num_count; j++)
{
RandomNumber = 0 + arc4random() % num_count;
NSLog(#"%d",RandomNumber);
if ([arr_numbers count]>0)
{
if (![arr_numbers containsObject:[NSNumber numberWithInt:RandomNumber]])//
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
if (j == num_count-1)
{
if ([arr_numbers count] != num_count)
{
j = 0;
}
}
}
else
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
}
NSLog(#"%#",arr_numbers);

Resources