创建多个按钮而不重复代码?

时间:2014-08-27 21:57:50

标签: ios objective-c

我知道有一种比我的noob实现更好的方法。我尝试将4个按钮添加到具有4个不同CGrect的视图中,以便按钮一个堆叠在另一个上面。代码现在运行正常,但我很难将这些重复的代码转换为工作方法:

CGRect rect = CGRectMake(30.0f, 250.0f, 250.0f, 250.0f);
CGRect rect1 = CGRectMake(30.0f, 275.0f, 250.0f, 250.0f);
CGRect rect2 = CGRectMake(30.0f, 300.0f, 250.0f, 250.0f);
CGRect rect3 = CGRectMake(30.0f, 325.0f, 250.0f, 250.0f);

enableAlarm = [[UIButton alloc] initWithFrame:rect];
[enableAlarm setTitle:firstTime forState:UIControlStateNormal];
[enableAlarm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[[self view] addSubview:enableAlarm];

enableAlarm1 = [[UIButton alloc] initWithFrame:rect1];
[enableAlarm1 setTitle:secondTime forState:UIControlStateNormal];
[enableAlarm1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[[self view] addSubview:enableAlarm1];

enableAlarm2 = [[UIButton alloc] initWithFrame:rect2];
[enableAlarm2 setTitle:thirdTime forState:UIControlStateNormal];
[enableAlarm2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[[self view] addSubview:enableAlarm2];

enableAlarm3 = [[UIButton alloc] initWithFrame:rect3];
[enableAlarm3 setTitle:fourthTime forState:UIControlStateNormal];
[enableAlarm3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[[self view] addSubview:enableAlarm3];

我觉得这可以放在一个简单的方法中,我可以打四次,但无法弄清楚如何做...

1 个答案:

答案 0 :(得分:4)

每次重复某事时,请尝试循环

CGRect rects = { {30.0f, 250.0f, 250.0f, 250.0f},
                {30.0f, 275.0f, 250.0f, 250.0f},
                {30.0f, 300.0f, 250.0f, 250.0f},
                {30.0f, 325.0f, 250.0f, 250.0f},
                };
NSString *titles = @[firstTime, secondTime, thirdTime, fourthTime];

NSMutableArray *enableAlarmButtons = [NSMutableArray array]; // if you want to access these buttons later
for (int i = 0; i < 4; ++i) { // you can use sizeof to avoid hardcode number
    UIButton  *enableAlarm = [[UIButton alloc] initWithFrame:rects[i]];
    [enableAlarm setTitle:titles[i]  forState:UIControlStateNormal];
    [enableAlarm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [[self view] addSubview:enableAlarm];
    [enableAlarmButtons addObject:enableAlarm];
}

如果只有y值改变

CGRect rect = CGRectMake(30.0f, 250.0f, 250.0f, 250.0f);
NSString *titles = @[firstTime, secondTime, thirdTime, fourthTime];

NSMutableArray *enableAlarmButtons = [NSMutableArray array]; // if you want to access these buttons later
for (int i = 0; i < 4; ++i) {
    UIButton  *enableAlarm = [[UIButton alloc] initWithFrame:rects[i]];
    [enableAlarm setTitle:titles[i]  forState:UIControlStateNormal];
    [enableAlarm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [[self view] addSubview:enableAlarm];
    [enableAlarmButtons addObject:enableAlarm];

    rect.origin.y += 25;
}