简体   繁体   中英

Create a function that is able to check the title of the button pressed

I have a loop for creating buttons dynamically.

for (int b = 0; b < _currentPlayerTeams.count; b++)
    {
        HNTeamObject *team = _currentPlayerTeams[b];
        CGFloat buttonY = 168 + ((b + 1) * distanceBetweenButtons) - 23;

        NSString *buttonTitle = [NSString stringWithFormat:@"%@ %@",team.teamName, team.seriesName];

        UIButton *button = [[UIButton alloc] init];
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:[UIImage imageNamed:@"images.png"] forState:UIControlStateNormal];
        button.titleLabel.textColor = [UIColor blackColor];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor clearColor];
        [button addTarget:self
                   action:@selector(chooseTeamOne:)
         forControlEvents:UIControlEventTouchUpInside];
        [button setTitle: buttonTitle forState:UIControlStateNormal];
        button.titleLabel.text = (@"%@", buttonTitle);
        button.frame = CGRectMake(labelAndButtonX, buttonY, 268.0, 46.0);
        [self.view addSubview:button];
    }

I need to make a function that can act as the selector that for each button that is created and look at the button's title. Since I am making the buttons in the loop they are local and do not appear in another function that I create. Any help would be appreciated. I apologize in advance because I am very new to coding and am not quite up to speed with what is going on. Thanks.

Each button will call the chooseTeamOne: function when it is pressed so I assume you want to get the buttons title in that method.

To do so, use the UIButton's title property:

 NSLog(@"%@", button.currentTitle);

This will log the button's current title. What is important to note is that I am referencing "button" which is the instance of the UIButton which called the chooseTeamOne method. I am assuming chooseTeamOne takes a UIButton button as a parameter.

If your method takes an 'id' as a parameter you would need to cast the sent object to a UIButton like this:

- (IBAction)chooseTeamOne:(id)sender {
      UIButton *button = (UIButton *)sender; 
      NSString *buttonTitle = button.currentTitle;
  }

Do you need a separate selector to return the title? If not then..

I imagine that your chooseTeamOne function is something along the lines of:

-(IBAction)chooseTeamOne:(id)sender {
    ...do things...
}

in which case, just add

-(IBAction)chooseTeamOne:(id)sender {
    UIButton *button = sender;
    NSString *stringThatYouWant = button.titleLabel.text; //get the text on the button
    ...do things...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM