Get the number of switches set ON - ios

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);

Related

How to change multiple UILabel text colour while scrolling inside scrollview Objective-c iOS

Hi I am new to iOS development..Can any one help me..
I have added multiple UILabel inside UIScrollview based on array count..For example if array count is 3 means ..then In scrollview adding 3 view along with UILabel in each view..
So now 3 view having 3 different UILabels..
But now I want to change colour of UILabel text in different views based on requirement..but I am not able to update colour…
Its change colour of UILabel text only for last index ..
I have written code in ScrollViewDidScroll:(UIScrollView *)scrollView
Any suggestion ..
self.robotScrollView.contentSize = CGSizeMake(robotCounts*Robot_ScrollView_Width, kRobotSrollViewH);
for (int i=0; i<robotCounts; i++) {
self.robotLabel = [[UILabel alloc] initWithFrame:CGRectMake(Robot_ScrollView_Width*i, 0 , Robot_ScrollView_Width, kRobotSrollViewH)];
self.robotLabel.textAlignment = NSTextAlignmentCenter;
self.robotLabel.backgroundColor = [UIColor clearColor];
self.robotLabel.textColor = [UIColor blackColor];
[self.robotScrollView addSubview:self.robotLabel];
if (kRemoteManager.robotsArray.count == 0) {
self.robotLabel.text = #"";
break;
}
DeviceBase *robot = kRemoteManager.robotsArray[i];
self.robotLabel.text = [NSString stringWithFormat:#"%#",robot.dName];
}
self.robotScrollView.contentOffset = CGPointMake(Robot_ScrollView_Width*currentRobotIndex, 0);
Changing UIlabeltext color in below scrollviewdidscroll method
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView == self.scrollView)
{
self.pageControl.currentPage = (scrollView.contentOffset.x+(scrollView.width/2)) / scrollView.width;
kRemoteManager.currentIndex = self.pageControl.currentPage;
[[NSNotificationCenter defaultCenter] postNotificationName:kNotify_Steward_ReloadData object:nil];
NSMutableArray *viewRemoteIDarray = [NSMutableArray array];
CardRemoteModel *model = kRemoteManager.cardRemoteArray[self.pageControl.currentPage];
if (![viewRemoteIDarray containsObject:#(model.remoteID)])
{
if (model.remoteType == kooKong_remoteType_AirCleaner || model.remoteType == kooKong_remoteType_AC)
{
self.robotLabel.textColor = [UIColor whiteColor];
}
else
{
self.robotLabel.textColor = [UIColor blackColor];
}
}
} else if (scrollView == self.robotScrollView) {
kRemoteManager.currentRobotIndex = (scrollView.contentOffset.x+(scrollView.width/2)) / scrollView.width;
self.leftBtn.hidden = NO;
self.rightBtn.hidden = NO;
if (kRemoteManager.currentRobotIndex == kRemoteManager.robotsArray.count-1) {
self.rightBtn.hidden = YES;
}
if (kRemoteManager.currentRobotIndex == 0){
self.leftBtn.hidden = YES;
}
}
}
There are three labels, but only one label property. The last one assigned is the only one you'll have access to later. One solution would be to keep an array of labels in the view controller.
#property(nonatomic, strong) NSMutableArray *labels;
In the posted method...
self.labels = [NSMutableArray array];
for (int i=0; i<robotCounts; i++) {
UILabel *robotLabel = [[UILabel alloc] initWithFrame:CGRectMake(Robot_ScrollView_Width*i, 0 , Robot_ScrollView_Width, kRobotSrollViewH)];
[self.labels addObject:robotLabel]; // <--- new
robotLabel.textAlignment = NSTextAlignmentCenter;
robotLabel.backgroundColor = [UIColor clearColor];
robotLabel.textColor = [UIColor blackColor];
[self.robotScrollView addSubview:robotLabel];
if (kRemoteManager.robotsArray.count == 0) {
robotLabel.text = #"当前无酷控机器人";
break;
}
DeviceBase *robot = kRemoteManager.robotsArray[i];
robotLabel.text = [NSString stringWithFormat:#"%#",robot.dName];
}
To change all of the colors:
- (void)setLabelColors:(UIColor *)color {
for (UILabel *label in self.labels) {
label.textColor = color;
}
}
Another idea would be to give each label a tag, and find them when you need them.
for (int i=0; i<robotCounts; i++) {
self.robotLabel = [[UILabel alloc] initWithFrame:CGRectMake(Robot_ScrollView_Width*i, 0 , Robot_ScrollView_Width, kRobotSrollViewH)];
self.robotLabel.tag = i+1;
// the remainder of this loop as you have it
To change all the colors...
- (void)setLabelColors:(UIColor *)color {
for (int i=0; i<robotCounts; i++) {
UILabel *label = (UILabel *)[self.robotScrollView viewWithTag:i+1];
label.textColor = color;
}
}

Xcode: Remove an array of textiews from screen

I'm currently adding 5 textviews onto the viewcontroller programatically inside the viewDidLoad method.
for (int i = 0; i < 5; i++) {
//Add 5 textviews
UITextView *reqTV = [[UITextView alloc] initWithFrame:CGRectMake(30,30,250,50)];
reqTV.text = #"This is a textview";
[self.view addSubview:reqTV];
}
If later, I want to delete (not hide) these 5 textviews with a button click, how would I do that?
I have thought of using this, but am not sure how to call all 5 textviews to delete them.
- (void)removeTextViewButton:(id)sender {
[reqTV removeFromSuperview]; //remove textview
}
Thank you.
I see two easy ways:
You can save your textViews inside array as ivar of your controller.
And later remove each textView in array.
for (int i = 0; i < 5; i++) {
...
[textViews addObject: reqTV];
...
}
- (void)removeTextViewButton:(UIButton *)sender {
[textViews makeObjectsPerformSelector:#selector(removeFromSuperview)];
}
2. Assign static tag for each textView:
for (int i = 0; i < 5; i++) {
...
reqTV.tag = 1001; // for example
}
- (void)removeTextViewButton:(UIButton *)sender {
NSArray *subs = [NSArray arrayWithArray: self.view.subviews];
for (UIView *sub in subs) {
if (sub.tag == 1001) {
[sub removeFromSuperview];
}
}
}
Used code below to remove UITextViews:
- (void)removeTextViewButton:(id)sender {
NSArray *reqTVViews = [NSArray arrayWithArray: self.view.subviews];
for (UIView *tvView in reqTVViews) {
if ([tvView isKindOfClass:[UITextView class]]) {
[tvView removeFromSuperview];
}
}
}
When you are adding UITextFields on viewController use tag value to uniquely identify each textField.
You can store each tag value in an array for further use, eg.
#property (nonatomic, strong) NSMutableArray *tagArray;
NSMutableArray *tagArray = [NSMutableArray array];
for (int i = 101; i <= 105; i++ ) {
UITextField *txt = [UITextField alloc] init]; //for eg.
...
...
txt.tag = i;
[arr addObject:[NSNumber numberWithInt:i]];
[self.view addSubView:txt];
}
When you want to delete any of the textField or all then...
UIView *view = [self.view viewWithTag:<tag value>];
[view removeFromSuperview];
eg.
for (int i = 0; i < tagArray.count; i++) {
NSInteger tag = [[arr objectAtIndex:i] intValue];
UITextField *txt = (UITextField *)[self.view viewWithTag:tag];
[txt removeFromSuperview];
}
You can remove all subview in one go
- (void)removeTextViewButton:(id)sender
{
for (UIView *subview in views.subviews)
{
[subview removeFromSuperview];
}
}
Happy Coding.. :)

Get id stepper added programmatically

I want to add an action to a stepper added programmatically, but I don't know how to get which stepper is clicked. I have a NSMutableArray where I change the values, but I want to know which stepper is clicked. Here is my code:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
for (int i = 0; i < count; i++) {
//Here I create the stepper
UIStepper *steperCode = [[UIStepper alloc] initWithFrame:CGRectMake(40, (i*30)+120, 300, 200)];
steperCode.maximumValue = 1000;
steperCode.minimumValue = 0;
steperCode.stepValue=1.0;
[self.view addSubview:steperCode];
}
Try this
- (void)viewDidLoad
{
[super viewDidLoad];
for (int i = 0; i < count; i++)
{
UIStepper * stepperCode = [[UIStepper alloc] initWithFrame:CGRectMake(140, 60, 300, 200)];
[steperCode addTarget:self action:#selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
stepperCode.maximumValue = 10;
stepperCode.minimumValue = 0;
stepperCode.stepValue=2.0;
stepperCode.tag = i;
[self.view addSubview:stepperCode];
}
}
- (IBAction)valueChanged:(UIStepper *)sender
{
NSLog(#"Changed stepper num :%i",sender.tag);
}

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

select a random button from array

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

Resources