gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:13:31 25 4
gpt4 key购买 nike

我知道有比我的菜鸟实现更好的方法来做到这一点。我正在尝试将 4 个按钮添加到具有 4 个不同 CGrects 的 View 中,以便按钮将一个堆叠在另一个之上。该代码现在工作正常,但我正在努力将这个重复的代码变成一种工作方法:

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];

我觉得这可以放在一个简单的方法中,我可以调用四次但不知道该怎么做......

最佳答案

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

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

关于ios - 创建多个按钮而不重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25537623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com