1

How do I set the title to each button so it sets the button title to: 1, 2, 3, 4 5 etc. button?

My buttons:

@interface PregnancyViewController () {
    NSMutableArray *buttons;
}

@end

- (void)viewDidLoad
{
    [super viewDidLoad];

        for( int i = 0; i < 5; i++ ) {
            for( int j = 0; j < 6; j++ ) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                button.frame = CGRectMake(j * 50 + 10, i * 50 + 20, 40, 40);

                // Add buttons to my mutable array
                [buttons addObject: button];

                [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:button];
            }
        }
}
1
  • did you try [button setTitle:...];? Commented Aug 23, 2013 at 13:52

1 Answer 1

2

How about this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUInteger k = 1;
    for( NSUInteger i = 0; i < 5; i++ ) {
        for( NSUInteger j = 0; j < 6; j++ ) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            button.frame = CGRectMake(j * 50 + 10, i * 50 + 20, 40, 40);
            NSString* title = [NSString stringWithFormat: @"%@", @(k++)];
            [button setTitle: title forState: UIControlStateNormal]; 
            // Add buttons to my mutable array
            [buttons addObject: button];

            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:button];
        }
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

If I use NSLog(@"%@", title); the log shows the number but the title on the button doesn't print out the numbers. Hm any idea why @ipmcc ?
aha! if I change: [button setTitle: title forState: ~0]; To: [button setTitle: title forState: 0]; The title shows on each button. what does the ~ sign mean @ipmcc
It means "bitwise NOT." The idea is that UIControlState is made up of flags, and I wanted to just set the title for all states, but apparently that doesn't work. So UIControlStateNormal it is... I guess it makes sense if its keeping a map of states->title.
How can I pass the title of the button to the method buttonPressed: so that I know which button in the array I'm pressing @ipmcc ?
Wow thanks @ipmcc! I'm new stackoverflow, is there a way I can like give you a star or something?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.