I have IBOutlets
for my UIButtons
like what is shown below. This is continued 30 times. I am wondering if there is a way to make it where I do not have to list each button outlet like this and make it more organized?
If anyone can point me in the right direction I will deeply appreciate it.
@property (weak,nonatomic) IBOutlet UIButton *level1Button;
@property (weak,nonatomic) IBOutlet UIButton *level2Button;
@property (weak,nonatomic) IBOutlet UIButton *level3Button;
Instead of lots of outlets, you can use an outlet collection. In your .h file:
@property (weak, nonatomic) IBOutletCollection(UIButton) NSArray *buttons;
Then, you can control-drag your buttons to that line and they will all be in the array, in the order that you dragged them.
Another option is (example with 6 UIButtons
):
Create the buttons. eg 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
}
}
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.