How to create buttons that add integers to a Mutable Array?

You can create instance variable of NSMutableArray and two buttons with setting tag value and on clicking the same you can add it to array.like that below:-

- (void)viewDidLoad 
{
    [super viewDidLoad];
    self.mutArr=[NSMutableArray array];
    NSUInteger j=0;
    for(NSUInteger i=0; i<2; i++)
    {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self
               action:@selector(buttonClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:[NSString  stringWithFormat:@"%@ %ld",@"Button",i+1] forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0+j, 210.0, 160.0, 40.0);
    [self.view addSubview:button];
    button.tag=i+1;
    j=100;
    }
}

-(void)buttonClicked:(id)sender
{
    [self.mutArr addObject:@([sender tag])];
    NSLog(@"%@",self.mutArr);
}

Leave a Comment