How to create UISwitch in for loop in iphone? - iphone

I have done following code in Viewdid Load for creating multiple switch programmatically.
float x =40.0, y=20.0,height=60.0,width=26.0;
for (int i =0; i < 3; i++) {
CGRect frame = CGRectMake(x, y, height, width);
UISwitch *switchControl = [[UISwitch alloc] initWithFrame:frame];
[switchControl addTarget:self action:#selector(flip:) forControlEvents:UIControlEventTouchUpInside];
[switchControl setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:switchControl];
y= y+50.0;
}
- (IBAction) flip: (id) sender {
UISwitch *onoff = (UISwitch *) sender;
NSLog(#"%#", onoff.on ? #"On" : #"Off");
}
After doing this code i am able to create multiple UISwitchs. Now i am not getting how to handle action on every switch. If anyone knows how to handle actions on all switchs please help me. I will appreciate to him/her. Thanks in advance.

for (int i =0; i < 3; i++) {
CGRect frame = CGRectMake(x, y, height, width);
UISwitch *switchControl = [[UISwitch alloc] initWithFrame:frame];
//add tag as index
switchControl.tag = i;
[switchControl addTarget:self action:#selector(flip:) forControlEvents: UIControlEventValueChanged];
[switchControl setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:switchControl];
y= y+50.0;
}
- (IBAction) flip: (id) sender {
UISwitch *onoff = (UISwitch *) sender;
NSLog(#"no.%d %#",onoff.tag, onoff.on ? #"On" : #"Off");
//use onoff.tag , you know which switch you got
}

it is UIControlEventValueChanged event
[switchControl addTarget:self action:#selector(flip:) forControlEvents:UIControlEventValueChanged];

Related

Pare the label text to next View when i clicked that Particular label from list label showed in view controller

I am trying to parse the text of particular label from list of label showed in UIScrollView into next view show in label. But these label text got from NSMutableArray. i tried but i got only last value of the NSMutableArray See following code for Ref: Plz suggest what i will do
-(void)dataPrinting
{
int t= 60;
NSLog(#"%#",totalData);
for (int i = 0; i < [totalData count]; i++)
{
pplname=[[UILabel alloc]initWithFrame:CGRectMake(10, t, 200, 30)];
pplname.backgroundColor=[UIColor clearColor];
pplname.text=[totalData objectAtIndex:i];
pplname.textColor=[UIColor redColor];
[scrollView addSubview:pplname];
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
//initWithFrame:CGRectMake(10, t, 200, 40) ];
button.frame=CGRectMake(10, t, 200, 40);
[button addTarget:self
action:#selector(nextview)
forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
t=t+40;
}
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width, t+2)];
[aview stopAnimating];
}
-(IBAction)nextview
{
Details *detailsPage=[[Details alloc]initWithNibName:#"Details" bundle:nil];
for (int i = 0; i < [totalData count]; i++)
{
detailsPage.pplName=[totalData objectAtIndex:i];
}
[self presentModalViewController:detailsPage animated:YES];
}
Give the tag to fetch particular name of label just replace my bellow code with your code...
-(void)dataPrinting
{
int t= 60;
NSLog(#"%#",totalData);
for (int i = 0; i < [totalData count]; i++)
{
pplname=[[UILabel alloc]initWithFrame:CGRectMake(10, t, 200, 30)];
pplname.backgroundColor=[UIColor clearColor];
pplname.text=[totalData objectAtIndex:i];
pplname.tag = i;
pplname.textColor=[UIColor redColor];
[scrollView addSubview:pplname];
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
//initWithFrame:CGRectMake(10, t, 200, 40) ];
button.frame=CGRectMake(10, t, 200, 40);
button.tag = i;
[button addTarget:self
action:#selector(nextview)
forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
t=t+40;
}
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width, t+2)];
[aview stopAnimating];
}
-(IBAction)nextview:(id)sender
{
UIButton *btnTemp = (UIButton*)sender;
Details *detailsPage=[[Details alloc]initWithNibName:#"Details" bundle:nil];
detailsPage.pplName=[totalData objectAtIndex:btnTemp.tag];
[self presentModalViewController:detailsPage animated:YES];
}

How to get the information about the sender in the case here

I am creating UIButtons inside a loop as shown below.
for(int i = 1; i <= count; i++){
if(i ==1){
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 40, 40)];
[btn1 setImage:image2 forState:UIControlStateNormal];
[self addSubview:btn1];
continue;
}
x = x + 40;
y = y + 50;
UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(x , y, 40, 40)];
[btn2 setImage:image1 forState:UIControlStateNormal];
[btn2 addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
}
And I handle the UIButton clicked events as
-(void) buttonPressed{
}
I need the information about which button I have clicked in the event handling method. I need to ge the frame of the clicked button. How can I alter this code to get the information about the sender.
Add a tag to your button while it is created like btn.tag=i; and re define your method like this
-(void) buttonPressed:(id)sender{
// compare sender.tag to find the sender here
}
What you should do is add these lines in your code:
for(int i = 1; i <= count; i++)
{
if(i ==1){
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 40, 40)];
[btn1 setImage:image2 forState:UIControlStateNormal];
[btn1 setTag:i]; // This will set tag as the value of your integer i;
[self addSubview:btn1];
continue;
}
x = x + 40;
y = y + 50;
UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(x , y, 40, 40)];
[btn2 setImage:image1 forState:UIControlStateNormal];
[btn2 setTag:i]; // also set tag here.
[btn2 addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
}
And now change your IBAction like this:
-(void) buttonPressed: (id)sender
{
if(sender.tag==1) // determine which button was tapped using this tag property.
{
// Do your action..
}
}
Or you can do it this way..This way you copy the object thats in sender to this UIBtton object.
-(void) buttonPressed: (id)sender
{
UIButton *tempBtn=(UIButton *) sender;
if(tempBtn.tag==1) // determine which button was tapped using this tag property.
{
// Do your action like..
tempBtn.backgroundColor=[UIColor blueColor];
tempBtn.alpha=0.5;
}
}
So in this parameter sender its going to hold your UIButton on which you interact and you can access its properties like tag, text etc. Hope it helps..

how to set multiple buttons in UIScrollView?

how to set multiple buttons in UIScrollView and also how to set clicked action for particular button index?
UIScrollView *view = ..;
UIButton *button1 = ... ;
button1.tag = 1;
UIButton *button2 = ... ;
button1.tag = 2;
UIButton *button3 = ... ;
button1.tag = 3;
[view addSubview:button1];
[view addSubview:button2];
[view addSubview:button3];
In IBAction method check button tag to identify clicked button.
you can call this(initScrollView) method on viewDidLoad
- (void)viewDidLoad {
arrayScrollViewImages = [[NSArray alloc] initWithObjects:
[[MyKeyValuePair alloc] initWithKey:#"imagename1" withValue:#"imagename1.png"],
[[MyKeyValuePair alloc] initWithKey:#"imagename2" withValue:#"imagename2.png"],nil];
[self initScrollView];
}
here arrayScrollViewImages is NSArray
- (void) initScrollView
{
int width = 10;
for (int index = 0; index < [arrayScrollViewImages count]; index++) {
MyKeyValuePair *pair = [arrayScrollViewImages objectAtIndex:index];
UIImage *image = [UIImage imageNamed:pair.value];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(width, 2, 34, 34)];
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTag:index];
[button addTarget:self action:#selector(scrollViewButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
if (index == 0) {
[button setBackgroundColor:[UIColor colorWithRed:0.59 green:0.38 blue:0.21 alpha:1.00]];
}
[scrollView addSubview:button];
width += 45;
}
scrollView.contentSize = CGSizeMake(width, 48);
scrollView.contentOffset = CGPointMake(0, 0);
}
- (void) scrollViewButtonTapped:(id)sender {
for (UIButton *b in scrollView.subviews) {
if ([b isKindOfClass:[UIButton class]]) {
[b setBackgroundColor:[UIColor clearColor]];
}
}
UIButton *button = (UIButton *) sender;
[button setBackgroundColor:[UIColor colorWithRed:0.59 green:0.38 blue:0.21 alpha:1.00]];
MyKeyValuePair *pair = [arrayScrollViewImages objectAtIndex:button.tag];
labelEspecialidad.text = pair.key;
}
here MyKeyValuePair is a one class
*MyKeyValuePair.h*
#interface MyKeyValuePair : NSObject {
NSString *key;
NSString *value;
}
// Properties
#property (nonatomic, retain) NSString *key;
#property (nonatomic, retain) NSString *value;
#end
MyKeyValuePair.m
#implementation MyKeyValuePair
#synthesize key, value;
- (id) initWithKey: (NSString *) _key withValue: (NSString *) _value {
if (self = [super init]) {
self.key = _key;
self.value = _value;
}
return self;
}
- (void) dealloc {
[super dealloc];
[self.key release];
[self.value release];
}
#end
Using XCode Interface Builder
Add buttons (select and drag&drop them from side objects panel)
Create IBAction for every button (in owner class .h and implement in .m)
Link buttons to actions via right mouse click&drag
See some video tutorials on youtube, such as
http://www.youtube.com/watch?v=WgAAvRQBrPc
http://www.youtube.com/watch?v=uAdmetwz7sc
http://www.youtube.com/watch?v=vixD-N6cbDY
and read Developer Guide
http://www.switchonthecode.com/tutorials/creating-your-first-iphone-application-with-interface-builder
http://developer.apple.com/library/ios/#documentation/IDEs/Conceptual/Xcode4TransitionGuide/InterfaceBuilder/InterfaceBuilder.html
You can use an array of buttons for that purpose. Assign a unique tag id to each button, and programmatically spread the buttons along the UIScrollView. Have the UIScrollView listen to the Touch Up Inside event, where you can then determine which button has been clicked by the unique tag ID.

how to creating dynamic buttons iphone xcode?

I want to create uibuttons dynamically. so i for loop to create button with tag and added to view.
all buttons performs the same action with respect to its tag value... but i want to change the propery of the button. Therefore i need to get the uibutton using the tag value...
my code...
UIButton *button2;
//view did load
int width = 30;
for(int i = 1; i <= 5; i++)
{
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:#selector(ratingAction:) forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[UIImage imageNamed:#"star1.png"] forState:UIControlStateNormal];
button2.tag = i;
button2.backgroundColor = [UIColor clearColor];
button2.frame = CGRectMake(width, 78, 15, 15);
[self.view addSubview:button2];
width = width +30;
}
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
}
Use viewWithTag function of UIView to access your UIButton using the tag value.
See in Documentation viewWithTag
Use it as below.
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:1];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:3];
UIButton* myButton = (UIButton*)[mySuperView viewWithTag:6];
.........
-(void)ratingAction:(id*)sender
{
// here using the tag value i want to get the button and change the background image….
// for example i want to change the background for tag values 1,3,6,7 ,8…
if ([sender isKindOfClass:[UIButton class]])
{
UIButton *temp=(UIButton*)sender;
if ([temp tag]==1 || [temp tag]==3 || [temp tag]==6 || [temp tag]==7 )
{
[temp setBackgroundColor:[UIColor redColor]];
}
}
}
Check this code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
int y = 100;
for (int i=0; i<=5; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80, y, 160, 40);
[button setTitle:[NSString stringWithFormat:#"Button-%i", i] forState:UIControlStateNormal];
// [button set
[self.view addSubview:button];
y=y+60;
}
}
-(void)aMethod:(id)sender{
UIButton *button = sender;
int y = 100;
int i = 5;
for (int x=0; x<=i; x++) {
NSString *frameString = [NSString stringWithFormat:#"{{80, %i}, {160, 40}}", y];
if ([NSStringFromCGRect(button.frame) isEqualToString:frameString]) {
NSLog(#"button %i clicked..", x);
}
y= y+60;
}
}

Setting Property on UIButton in Loop

I'm spinning in circles on the best way to implement this, so maybe you can help me out:
How can I make it so when the UIButton responds to the selector highlightImage, it also can set the desired challengeId = the index of my appDelegate.availableArray?
In my cellForRowAtIndexPath method, I'm creating a UIScrollView with buttons:
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, tv.frame.size.width, 78)];
[scrollView setContentSize:CGSizeMake(500, 78)];
[self createScrollButtons];
[[cell contentView] addSubview:scrollView];
My createScrollButtons loops and creates buttons in the scrollView as so, looping over the number of elements in my availableArray
- (void) createScrollButtons
{
SuperHeroGameAppDelegate *appDelegate = (SuperHeroGameAppDelegate *)[[UIApplication sharedApplication] delegate];
int x = 0;
int y = 0;
NSLog(#"Challenge array = %#",appDelegate.availableArray);
for (int i = 0; i < [appDelegate.availableArray count]; i++) {
NSLog(#" ID= %d", [[[appDelegate.availableArray objectAtIndex:i]valueForKey:#"id"] intValue]);
[self createButtonAtX:x AndY:y withChallenge:[[appDelegate.availableArray objectAtIndex:i]valueForKey:#"id"]];
x += 90;
}
}
createButtonAtX andY withChallenge is called for each element inavailableArray`, positioning them correctly along the scrollView.
- (void)createButtonAtX:(int) x AndY:(int) y withChallenge:(id)challengeId
{
CGRect buttonRect = CGRectMake(x, y, 80, 78);
ChallengeButton *capeButton = [ChallengeButton buttonWithType:UIButtonTypeCustom];
[capeButton setBackgroundColor:[UIColor clearColor]];
[capeButton setFrame:buttonRect];
[capeButton addTarget:self action:#selector(highlightImage:) forControlEvents:UIControlEventTouchUpInside];
UIImage *capeImage = [UIImage imageNamed:#"CapePower.png"];
[capeButton setBackgroundImage:capeImage forState:UIControlStateNormal];
[scrollView addSubview: capeButton];
}
highlightImage is called as each buttons selector, to determine which button is pressed. (and ideally with element from the availableArray that button is associated with)... I've subclasses UIButton and added an int value to be able to call [sender setChallengeId:]
- (void) highlightImage:(id)sender
{
if([sender isSelected] == NO){
[sender setSelected:YES];
[sender setChallengeId:selectedChallenge];
NSLog(#"sender = %d",[sender challengeId]);
UIImage *selectedImage = [UIImage imageNamed:#"PowerBarHand.png"];
[sender setBackgroundImage:selectedImage forState:UIControlStateSelected];
}
else {
[sender setBackgroundImage:[UIImage imageNamed:#"HandstandPower.png"] forState:UIControlStateNormal];
[sender setSelected:NO];
selectedChallenge = 0;
}
}
My problem is I cannot figure out how to get the appDelegate's availableArray element INTO my highlightImage, as UIButton's [capeButton addTarget:challengeId action:#selector(highlightImage:) forControlEvents:UIControlEventTouchUpInside] will not allow me to pass the challengeId from the loop earlier in the flow.
I am able to pass any integer value to setChallengeId, and it is handling as expected. I just need to get the appDelegate.availableArray id value from the loop.
Any direction would be great!:)
You get availableArray into highlightImage: the same way you got it into createScrollButtons:
SuperHeroGameAppDelegate *appDelegate = (SuperHeroGameAppDelegate *)[[UIApplication sharedApplication] delegate];
and then access appDelegate.availableArray.
I think that's not the question you actually meant to ask, though. I think what you want is to call setChallengeId: on each ChallengeButton as you create it in createButtonAtX:AndY:withChallenge:. Then in highlightImage: do selectedChallenge = [sender challengeId] rather than [sender setChallengeId:selectedChallenge].