Another option is (example with 6 UIButtons
):
Create the buttons. e.g in viewDidLoad
:
//This is an array with your buttons positions
self.cgPointsArray = @[[NSValue valueWithCGPoint:CGPointMake(25, 130)],[NSValue valueWithCGPoint: CGPointMake(70, 130)],
[NSValue valueWithCGPoint:CGPointMake(115, 130)],[NSValue valueWithCGPoint:CGPointMake(160, 130)],
[NSValue valueWithCGPoint:CGPointMake(205, 130)],[NSValue valueWithCGPoint:CGPointMake(250, 130)]];
// for loop to allocate the buttons
for (int i = 0; i < [self.cgPointsArray count]; i++)
{
NSValue *value = [self.cgPointsArray objectAtIndex:i];
CGPoint point = [value CGPointValue];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(point.x, point.y, 20, 20);
[button setBackgroundColor:[UIColor blueColor]];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.view addSubview:button];
}
Then you can manage the event through the tags
in:
- (void) buttonClicked: (id) sender
{
UIButton *tempButton = (UIButton*) sender;
int tag = tempButton.tag;
if (tag == 0)
{
//Do something
}
else if (tag == 1)
{
//Do something
}
else if (tag == 2)
{
//Do something
}
else if (tag == 3)
{
//Do something
}
else if (tag == 4)
{
//Do something
}
else if (tag == 5)
{
//Do something
}
}