0
-(void)mybuttonclick{
UGFloat p=120;
    for(int i=0;i<3;i++){   
        UIButton *aa = [UIButton buttonWithType:UIButtonTypeCustom];  
        if(i==0){        
            NSString *name=[[NSString alloc]initWithString@"ZERO"];
        }else if(i==1){
            NSString *name=[[NSString alloc]initWithString@"ONE"];
        }else if(i==2){
            NSString *name=[[NSString alloc]initWithString@"Two"];
        }else{
            NSString *name=[[NSString alloc]initWithString@"Three"];
        }
    [aa setFrame:CGRectMake(0.0f, 0.0f, 500.0f, 40.0f)];
    [aa setCenter:CGPointMake(100.0f,p)];
    [aa setBackgroundColor:[UIColor blueColor]];
    [aa addTarget:self action:@selector(fullscreen:)   forControlEvents:UIControlEventTouchUpInside];   
    [self.window addSubview:aa];
    p=p+50; 
    }
}

//----------------fullscreen method--------------------
-(void) fullscreen:(id)sender{

    NSLog(@"button pressed on %@",[sender Stringvalue]);
}

Here I created 3 UIButtons dynamically. When I press the first button I want to display ZERO. When pressing the second one, print ONE... then Two, then Three. How can I do this? I know it can be done using selector key work, but I don't know how.

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Raju
  • 3,459
  • 12
  • 37
  • 30

1 Answers1

1

You aren't telling the button about name anywhere. You could set it in the title buttons title with [aa setTitle:name forState:UIControlStateNormal]; then access it in fullscreen: with [sender currentTitle].

If you want the message to be independent of the title you could either make your own subclass of UIButton to store the message or have a different target action for each button.

Also, the way you are constructing the names is fragile. Something like this might be better:

NSArray* names = [NSArray arrayWithObjects:@"ZERO",
                                           @"ONE",
                                           @"Two",
                                           @"Three",
                                           nil];
for (NSString* name in names) {
    // Do stuff with name
}
Will Harris
  • 21,597
  • 12
  • 64
  • 64