我有我的游戏视图控制器UIButtons的IBOutlets需要更好地组织

时间:2014-04-03 22:15:30

标签: ios objective-c uibutton uistoryboard iboutlet

我的IBOutlets UIButtons就像下面显示的那样。这是持续30次。我想知道是否有办法让它成为我不必列出每个按钮插座的地方,让它更有条理?

如果有人能指出我正确的方向,我会非常感激。

@property (weak,nonatomic) IBOutlet UIButton *level1Button;
@property (weak,nonatomic) IBOutlet UIButton *level2Button;
@property (weak,nonatomic) IBOutlet UIButton *level3Button;

2 个答案:

答案 0 :(得分:2)

您可以使用插座集合代替大量插座。在你的.h文件中:

@property (weak, nonatomic) IBOutletCollection(UIButton) NSArray *buttons;

然后,您可以控制 - 将按钮拖动到该行,它们将按照您拖动它们的顺序存在于数组中。

答案 1 :(得分:0)

另一种选择是(例如6 UIButtons):

创建按钮。例如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];
}

然后,您可以通过以下tags管理事件:

- (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
    }

}