我将有一个 10x10 网格的 UIButton 对象。每个 UIButton 都需要通过行号和列号来引用,因此它们可能应该存储在某种类型的数组中。
我的问题:创建这个网格的最简单方法是什么?以编程方式还是通过 Interface Builder?如果以编程方式,访问这些按钮的最简单方法是什么,以便当触摸它们时,我能知道触摸按钮的行号和列号吗?
我个人不喜欢IB,所以我建议以编程方式进行!
使用 NSArray 来存储您的 UIButton。每个按钮的索引是row*COLUMNS+column
.
将标签属性设置为 BASE+index (BASE 是任意值 > 0),以便您可以找到按钮的位置:index=tag-BASE; row=index/COLUMNS; column=index%COLUMNS;
- (void)loadView {
[super loadView];
for (NSInteger row = 0; row < ROWS; row++) {
for (NSInteger col = 0; col < COLS; col++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonArray addObject:button];
button.tag = BASE + row * COLS + col;
button.frame = ...;
[button addTarget:self action:@selector(didPushButton:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:button];
}
}
}
- (void)didPushButton:(id)sender {
UIButton *button = (UIButton *)sender;
NSInteger index = button.tag - BASE;
NSInteger row = index / COLS;
NSInteger col = index % COLS;
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)