我想知道以下代码段究竟是如何工作的(是的,它确实按预期工作,并且根据单击的按钮给出了不同的标签值。关键是:我们不是重复使用button
7次吗,其他6个按钮还剩下哪里?执行此代码后,我们真的保留了 7 UIButton
秒的内存吗?
或者作为一个更普遍的问题:这是好的编程风格吗?关键是我需要根据单击的按钮进行不同的操作,而这种方法(以我有限的 objc 技能)看起来是最直接的。提前感谢,一个初入云的 iOS 开发者。
UIButton *button;
for(int k=0;k<7;k++)
{
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"" forState:UIControlStateNormal];
button.frame = CGRectMake(80, 20+30*k, 30, 30);
button.backgroundColor=[UIColor clearColor];
button.tag=k;
[subview addSubview:button];
}
其中函数 aMethod: 定义为:
-(IBAction)aMethod:(id)sender
{
UIButton *clickedButton=(UIButton *) sender;
NSLog(@"Tag is: %d",clickedButton.tag);
}
不,您没有重用UIButton
七次:循环的每次迭代都会在调用类方法buttonWithType:
时创建一个新的UIButton
实例,并将其分配给同名的变量:
[UIButton buttonWithType:UIButtonTypeCustom];
如果您在循环中声明该变量,您的代码会更好:
for(int k=0;k<7;k++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
// ...the rest of the loop
}
对于按钮执行非常相似的操作的情况,这是一种非常好的编程风格。例如,计算器按钮的区别仅在于它们插入的数字。当按钮执行差异很大的操作(例如插入与删除)时,您最好单独创建它们,而不是循环创建它们,并使用不同的方法为其单击提供服务。
在此代码中,您只需创建 7 个具有不同位置和标签的按钮。它更好,然后复制创建代码 7 次。我可以为您提供的一件事 - 为按钮标签创建一些枚举以防止这样的代码:
switch([button tag])
{
case 1:
// do something
break;
case 2:
// do something else
break;
case 3:
// exit
break;
.....
default:
assert(NO && @"unhandled button tag");
}
带有枚举值的代码更易于阅读
switch([button tag])
{
case kButtonForDoSomething:
// do something
break;
case kButtonForDoSomethingElse:
// do something else
break;
case kButtonExit:
// exit
break;
.....
default:
assert(NO && @"unhandled button tag");
}
这段代码就足够了,您正在创建 7 个不同的按钮并将它们添加为子视图。-addSubview:
后,对象将添加到数组中,通过 UIView
的 .subviews
属性访问。
虽然你应该在你的 for 循环中添加 UIButton *按钮。所以你的代码应该如下所示。
for(int k=0;k<7;k++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
....
}
如果您需要使用按钮执行 for 循环out
的操作,那么在循环外声明它是有意义的,但这不是您的情况。希望这有帮助。