select a random button from array - ios

I have to hide one of mine four UIButtons, randomly selected, BUT Excepting one.
for this, I created a NSMutableArray, and added all button there, as following example:
rand_btns = [[NSMutableArray alloc] initWithObjects: _bt1, _bt2, _bt3, _bt4,nil];
No, each button has its own tag: _bt1 has tag 1, _bt2 has tag 2, and so...
Please, any ideas? I want to hide one random button, but excepting a button which has tag equal to my: int Level.
I want to use this for a Quiz App.
So, my int Level is from 1-4 random number, when one of mine four buttons has tag equal to mine int Level, that button should be excepted from hiding.

Try this
-(void)randomSelForLevel:(NSInteger)level
{
int randomTag = rand() % 4;
while (randomTag == level) {
randomTag = rand() % 4;
}
for (int i=0; i<[rand_btns count]; i++) {
[[rand_btns objectAtIndex:randomTag] setHidden:NO];
}
[[rand_btns objectAtIndex:randomTag] setHidden:YES];
}

Just do this.
int randomTag = rand() % 4;
while (randomTag == Level) {
randomTag = rand() % 4;
}
[[randButtons objectAtIndex:randomTag] setHidden:YES]

to select random no between two no use this code:
int random = lowno + arc4random() % (highno-lowno);
Thanks.

abarr = [[NSMutableArray alloc]init];
for (int i = 0; i < 5; i++){
ab = [[UIButton alloc]init];
ab = [UIButton buttonWithType:UIButtonTypeRoundedRect];
ab.tag = i;
[ab setTitle:[NSString stringWithFormat:#"%ld",ab.tag] forState:UIControlStateNormal];
[ab addTarget:self action:#selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
[ab sizeToFit];
ab.backgroundColor = [UIColor yellowColor];
[abarr addObject:ab];
[self.view addSubview:ab];
switch (ab.tag) {
case 0:
ab.frame=CGRectMake(0, 0, 50,50);
break;
case 1:
ab.frame=CGRectMake(50, 0, 50,50);
break;
case 2:
ab.frame=CGRectMake(100, 0, 50,50);
break;
case 3:
ab.frame=CGRectMake(150, 0, 50,50);
break;
default:
break;
}
}
randomTag = rand() % 4;
for (int i=0; i<[abarr count]; i++) {
[[abarr objectAtIndex:randomTag] setBackgroundColor:[UIColor redColor]];
}
[[abarr objectAtIndex:randomTag] setBackgroundColor:[UIColor redColor]];
}
-(void)clicked:(UIButton*)button
{
NSLog(#"%ld",(long int)[button tag]);
for (int i=0; i<[abarr count]; i++)
{
[[abarr objectAtIndex:randomTag] setHidden:YES];
}
}

Related

Change BG color of a view with tap recogniser

I've created a view using for loop and if I click on a view ,Its background Color should change and Ive Achieved this, but when I click on another view the previous color remains the same.
my code
_dropDownView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3.5, -SCREEN_WIDTH, SCREEN_WIDTH/2+33, SCREEN_WIDTH - 100)];
for(int index = 0 ; index < indexCount ; index++)
{
_dropDownViewCell = [[UIView alloc] initWithFrame:CGRectMake(0, index * dropCellHeight, SCREEN_WIDTH, dropCellHeight)];
//Set Tag for future identification
[_dropDownViewCell setTag:index];
[_dropDownViewCell setBackgroundColor:[UIColor clearColor]];
[_dropDownView addSubview:_dropDownViewCell];
selectDropCell =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(dropCellAction:)];
[_dropDownViewCell addGestureRecognizer:selectDropCell];
}
- (void)dropCellAction:(UITapGestureRecognizer *)recognizer
{
switch (recognizer.view.tag) {
case 0: {
selectDropCell.view.tag = 0;
}
break;
case 1: {
selectDropCell.view.tag = 1;
}
break;
case 2: {
selectDropCell.view.tag = 2;
}
break;
case 3: {
selectDropCell.view.tag = 3;
}
break;
case 4: {
selectDropCell.view.tag = 4;
}
break;
case 5: {
selectDropCell.view.tag = 5;
}
break;
case 6: {
selectDropCell.view.tag = 6;
}
break;
default:
break;
}
for(int index = 0 ; index < 6 ; index ++){
NSUInteger slectedIndex = selectDropCell.view.tag;
if(slectedIndex == index)
{
recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
}
}
}
Achieved : While clicking the view Bg Color Change.
Problem : While clicking another View the Previous Bg Color should reset to the Original Color.
How Can I Solve this Problem ?
use this else condition
if(slectedIndex == index)
{
recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
}
else
{
recognizer.view.backgroundColor = [UIColor clearColor];//or your desired color
}
You have to reset last updated background color to clearColor.
You can achieve this by,
NSUInteger selectedIndex = selectDropCell.view.tag;
UIView *view = [self.view viewWithTag: index]; //self.view means _dropDownViewCell's view (parent view)
if(selectedIndex == index)
{
view.backgroundColor = [UIColor purpleMediumColor];
}
else
{
view.backgroundColor = [UIColor clearColor];
}
Note: I corrected spelling selectedIndex and setPurpleMediumColor
to purpleMediumColor
This is so easy!
Just create an instance to store your last selected view.
#property UIView *lastSelectedView;
And store it at your last for-loop
for(int index = 0 ; index < 6 ; index ++){
NSUInteger slectedIndex = selectDropCell.view.tag;
if(slectedIndex == index)
{
recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
if (self.lastSelectedView)
self.lastSelectedView.backgroundColor = [UIColor clearColor];
self.lastSelectedView = recognizer.view;
}
}
Just modify your last for-loop as above anyway.
Edit:
You can remove the for-loop actually because that's no meaning.
recognizer.view.backgroundColor = [UIColor setPurpleMediumColor];
if (self.lastSelectedView)
self.lastSelectedView.backgroundColor = [UIColor clearColor];
self.lastSelectedView = recognizer.view;
so you code will look like this.

Change Button Text Color Programmatically for n number of buttons without changing Text Color of other button

I have n number of buttons in the scrollView. If click on a button its text color is changing but if I click another button the text color of the previous button remain unchanged. I want to change the previous button text color as default color while clicking another button. The behavior will be just like a segmented control. Please help me regarding this, I've providing my code below:
-(void) loadScrollView:(CGRect)scrollViewFrame withButtonArray:(NSArray*)buttonArray withCase: (int)ButtonCase
{
scrollView=[[UIScrollView alloc]initWithFrame:scrollViewFrame];
[scrollView setScrollEnabled:YES];
[scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setContentSize:CGSizeMake(100 * 768, 40)];
for (int i = 0; i < [buttonArray count]; i++)
{
adButtonOutLet = [[UIButton alloc] initWithFrame:CGRectMake(140*i, 0, 135, 40)];
if (ButtonCase==0) {
[adButtonOutLet setBackgroundColor:UIColorFromRGB(0X272c2f)];
[adButtonOutLet setTitleColor:UIColorFromRGB(0x969696) forState:UIControlStateNormal];
}
else
{
if (i==0) {
adButtonOutLet.backgroundColor=UIColorFromRGB(0x000000) ;
[adButtonOutLet setTitleColor:UIColorFromRGB(0x179d95) forState:UIControlStateNormal];
}
}
adButtonOutLet.titleLabel.font=[UIFont fontWithName:#"MyriadPro" size:14.0];
[adButtonOutLet setTitle:[buttonArray objectAtIndex:i] forState:UIControlStateNormal];
adButtonOutLet.userInteractionEnabled= YES;
[adButtonOutLet setTag:i];
[adButtonOutLet addTarget:self action:#selector(adButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:adButtonOutLet];
[self.view addSubview:scrollView];
}
}
Here is my action method:
-(void)adButtonAction:(UIButton*)sender
{
for (int i = 0; i < [menuArray count]; i++)
{
int prevTag = 0;
if (sender.tag == i && Case==0)
{
[self reloadScrollViewwithButtonTag:i];
// [sender setSelected:YES];
sender.backgroundColor=UIColorFromRGB(0x000000) ;
[sender setTitleColor:UIColorFromRGB(0x179d95) forState:UIControlStateNormal];
prevTag=i;
}
if (Case==1) {
sender.backgroundColor=UIColorFromRGB(0x000000) ;
[sender setTitleColor:UIColorFromRGB(0x179d95) forState:UIControlStateNormal];
if (sender.tag==prevTag-1) {
[sender setBackgroundColor:UIColorFromRGB(0X272c2f)];
[sender setTitleColor:UIColorFromRGB(0x969696) forState:UIControlStateNormal];
}
}
}
}
Why don't you try changing all buttons style to no selected except the one that is on the sender parameter (selected button)?
-(void)adButtonAction:(UIButton*)sender{
for (int i = 0; i < [menuArray count]; i++)
{
if (sender == menuArray[i])
{
//Selected code style
}
else{
//No selected code style
}
}
}
Considering menuArray is an array with all buttons.
This way you check and modify all styles when a button is pressed.
Hope this could help you or at last give you a clue for resolve your problem.
I don' understand everything in your adButtonAction (what is menuArray?) method but I think what you need is simple, just adapt it to your method.
First create a NSMutableArray to keep reference on your button list:
for (int i = 0; i < [buttonArray count]; i++)
{
adButtonOutLet = [[UIButton alloc] initWithFrame:CGRectMake(140*i, 0, 135, 40)];
[myButtonArray addObject:adButtonOutlet];
....
Then in you action method, set the right color:
for (UIButton* b in myButtonArray){
if(b.tag == sender.tag){
[self setSelectedColor:YES forButton:b];
// Do what you want here
}
else{
[self setSelectedColor:NO forButton:b];
}
}
With:
-(void)setSelectedColor:(BOOL)selected forButton:(UIButton)button{
if(selected){
sender.backgroundColor=UIColorFromRGB(0x000000) ;
[sender setTitleColor:UIColorFromRGB(0x179d95) forState:UIControlStateNormal];
}
else{
[sender setBackgroundColor:UIColorFromRGB(0X272c2f)];
[sender setTitleColor:UIColorFromRGB(0x969696)forState:UIControlStateNormal];
}
}
Apply state vise( Normal,Selected ) title color of button.
Just persist a selected button reference as weak.
while user clicked on button set that button state as selected instead normal.
Change last selected button state Normal instead Selected.
Check out below code that will be help you
UIButton *selectedButton;
-(void)adButtonAction:(UIButton*)sender
{
UIButton *tempButton = sender;
if (selectedButton && selectedButton!=tempButton)
{
[selectedButton setSelected:NO];
}
[tempButton setSelected:YES];
selectedButton = tempButton;
}

how to pass multiple tags to addTarget:action:forControlEvents?

I know the code i have written is wrong. but i want something like this. How to do it?
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
int totalcout = 0;
int passValue ;
for(int j=0; j<5; j++{
for(int i=0; i<5; i++)
{
totalcout++;
if(totalcount >1){
break;
}else{
passValue = i;
}
}
button.tag = j;
[button addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction) button:(UIButton *)sender {
NSLog(#"tag numbers are %d", sender.tag);
detailViewController.mutableArray1 = [oneMutableArray objectAtIndex:sender.tag];
detailViewController.mutableArray2 = [twoMutableArray objectAtIndex:passValue];
}
I hope the question is clear.
Thank you in advance
i got your question.. you can't directly assign two tags to any UIView or any subclass directly. but you can achieve indirectly
may this code helps to achieve your intension to get two tags at the end
#define First_Tag 100
#define Second_Tag 200
-(void)createButton
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = ((First_Tag*10000)+30000)+(Second_Tag*10);
[button addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
}
- (void) button:(UIButton *)sender
{
int intTag2 = ((sender.tag-30000)%10000)/10;
int intTag1 = ((sender.tag-(intTag2*10))-30000)/10000;
NSLog(#"tag numbers are %d and %d", intTag1, intTag2);
}
I've used several big numbers to encode the tag .. hope it solves your problem to assign two tags

Get the number of switches set ON

I have this method bellow. Is there any way I can count UISwitches which are set on? Thanks!
while (i < numberOfAnswers) {
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
mySwitch.tag = i;
[_answerView addSubview:mySwitch];
i++;
}
I think that it'd be better if you keep references to switches.
NSMutableArray *switches = [NSMutableArray array]; // You can do that as property
while (i < numberOfAnswers) {
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
mySwitch.tag = i;
[_answerView addSubview:mySwitch];
i++;
[switches addObject:mySwitch];
}
Then later you don't have to iterate through every subview in view but you can iterate just switches array.
int count = 0;
for (UISwitch *switch in switches)
{
if (switch.isOn)
{
count += 1;
}
}
I like Piotr's solution, but if you really just want to know how many switches are on, you can also add this line to your initialization loop:
[mySwitch addTarget:self action:#selector(switchValueDidChange:) forControlEvents:UIControlEventValueChanged];
add a property to your class:
#property (nonatomic) int onCounts
And then this method:
-(void)switchValueDidChange:(UISwitch)sender {
self.onCounts = sender.on ? self.onCounts + 1 : self.onCounts - 1;
}
Now you can access the onCount property at any time to know how many switches are on.
Try
int count = 0;
for (UIView *subview in _answerView.subviews) {
if ([subview isKindOfClass:[UISwitch class]]) {
UISwitch *sw = (UISwitch*)subview;
count += sw.isOn ? 1 : 0;
}
}
here your code
int count = 0;
for (int i = start_switch_tag;i< numberOfAnswers;i++) {
if (((UISwitch *)[_answerView viewWithTag:i]).isOn) count ++;
}
NSLog(#"number of switches set ON: %d", count);

Unable to replace the tags of UIButton(s)

I have say for example 7 UIButtons namely c1 to c7. Now I have assigned tags starting from 1 to 7 respectively for the UIButtons c1 to c7.
Now when I select c2 for example it is removed from superView so now the tag for c2 which was 2 is transferred to c3 , 3 to c4 and so on.
This is what I have tried but logic is not working properly. I have posted question with similar concern before but didn't get any proper response.
-(void)totesttheFunction
{
for(int i=0; i<7; i++)
{
UIButton *testHere = (UIButton*)[self.view viewWithTag:i];
if([testHere isSelected])
{
int backuptagFor = testHere.tag;
CGFloat diff = 30.0;
for(int j=i+1; j<7;j++)
{
UIButton *btnToReplace = (UIButton*)[self.view viewWithTag:j];
CGRect setRect = CGRectMake(btnToReplace.frame.origin.x-diff, btnToReplace.frame.origin.y, btnToReplace.frame.size.width, btnToReplace.frame.size.height);
btnToReplace.tag = backuptagFor;
[testHere removeFromSuperview];
}
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
for(int itemIndex = 1; itemIndex <= 7; itemIndex++)
{
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(itemIndex*40, 10, 30, 30)];
btn.tag = itemIndex;
[self.view addSubview:btn];
if (itemIndex == 3 ||itemIndex == 4)
{
[btn setSelected:YES];
}
}
[self testFunction];
}
- (void)testFunction
{
int totalButtons = 7;
int totalRemovedButtons = 0;
for(int itemIndex = 1; itemIndex <= totalButtons; itemIndex++)
{
UIButton *testHere = ([[self.view viewWithTag:itemIndex] isKindOfClass:[UIButton class]])?(UIButton *)[self.view viewWithTag:itemIndex]:nil;
if([testHere isSelected])
{
[testHere removeFromSuperview];
NSLog(#"removed button with tag:%d",itemIndex + totalRemovedButtons);
for (int tempItemIndx = itemIndex + 1; tempItemIndx <= totalButtons; tempItemIndx++)
{
UIButton *nextButton = ([[self.view viewWithTag:tempItemIndx] isKindOfClass:[UIButton class]])?(UIButton *)[self.view viewWithTag:tempItemIndx]:nil;
nextButton.tag = tempItemIndx - 1;
}
itemIndex--;
totalRemovedButtons ++;
}
NSLog(#"loop run %d",itemIndex);
}
NSLog(#"-------------------------------------------------------------------");
//Checking the updated tags.
for(int itemIndex = 1; itemIndex <= (totalButtons - totalRemovedButtons); itemIndex++)
{
UIButton *testHere = ([[self.view viewWithTag:itemIndex] isKindOfClass:[UIButton class]])?(UIButton *)[self.view viewWithTag:itemIndex]:nil;
NSLog(#"New tags %d",testHere.tag);
}
}
Output:
loop run 1
loop run 2
removed button with tag:3
loop run 2
removed button with tag:4
loop run 2
loop run 3
loop run 4
loop run 5
loop run 6
loop run 7
---------------------
New tags 1
New tags 2
New tags 3
New tags 4
New tags 5
Apply below approach first delete old UI and re-generate new UI from scratch assign them same tags again
e.g. 123456 - No 4 deleted - 12356 - store remaining data - re-generate new UI from old data
now 12345
- (IBAction)actionDeletePrevEmp:(UIButton *)sender
{
// ********* DELETED OLD UI AND GENERATED DATA FROM OLD UI **********
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
for (int BTNCounter = 1; BTNCounter < 8 ;BTNCounter++)
{
if (BTNCounter == sender.tag)
{ // do not add contents to array
// delete it from UI
[(UIButton *)[self.view viewWithTag:BTNCounter]removeFromSuperview];
continue;
}
}
// ************* GENERATING NEW UI WITH TEMP DATA **************
int empSizeCounter = 50;
for (int loopCounter = 0, BTNTagCounter = 1 ; BTNTagCounter < 7; loopCounter++)
{
viewPreviousEmployerList = [[UIView alloc]initWithFrame:CGRectMake(0.0, empSizeCounter, 320.0, 50.0)];
// viewPreviousEmployerList.backgroundColor = [UIColor blackColor];
deletePrevEmpButton = [UIButton buttonWithType:UIButtonTypeSystem];
//[deletePrevEmpButton setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
deletePrevEmpButton = [[UIButton alloc]initWithFrame:CGRectMake(264.0, 10.0, 30.0, 30.0)];
deletePrevEmpButton.backgroundColor = [UIColor blueColor];
deletePrevEmpButton.titleLabel.text = #"X";
deletePrevEmpButton.tag = BTNTagCounter;
if (loopCounter+1 > [tempArray count])
{
btnTemp.text = #"";
}
else
{
btnTemp.text = tempArray[loopCounter];
}
BTNTagCounter++;
[viewPreviousEmployerList addSubview:btnTemp];
[self.viewAddEmployer addSubview:viewPreviousEmployerList];
empSizeCounter = empSizeCounter + 50;
}
First you need to add all button in NSMutableArray and follow me, (here array name is _myArrayOfBtn)
Add button's method such like, (and make sure that each button's have same method name)
[myBuutonName addTarget:self action:#selector(totesttheFunction:) forControlEvents:UIControlEventTouchUpInside];
And method declaration is like,
-(void) totesttheFunction:(UIButton *)sender
{
[sender removeFromSuperview]; // just put this code.
[_myArrayOfBtn removeObjectAtIndex:sender.tag];
// replace tag of buttons
for(int i = 1; i < _myArrayOfBtn.count; i ++)
{
UIButton *btn = (UIButton *)[_myArrayOfBtn objectAtIndex:i]
btn.tag = i;
}
}

Resources