构建10x10 UIButtons网格的最佳方法是什么?

Jam*_*ore 6 iphone objective-c

我将要有一个10x10的UIButton对象网格.这些UIButton中的每一个都需要由行号和列号引用,因此它们应该存储在某种类型的数组中.

我的问题:创建这个网格的最简单方法是什么?以编程方式或通过Interface Builder?如果以编程方式,访问这些按钮的最简单方法是什么,以便在触摸它们时,我能够知道触摸按钮的行号和列号?

squ*_*art 13

我个人不喜欢IB,所以我建议以编程方式进行!

使用NSArray存储您的UIButton.每个按钮的索引是row*COLUMNS+column.

将tag属性设置为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;
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Tyl*_*ler 8

您可以使用来自moriarty库的GridView 来帮助进行布局 - 将每个按钮定位在您想要的位置.部分地将squelart的示例代码构建为createButtonAtRow:col:方法,这可以如下工作:

GridView* gridview = [[GridView alloc] initWithRows:ROWS cols:COLS];
for (NSInteger row = 0; row < ROWS; ++row) {
  for (NSInteger col = 0; col < COLS; ++col) {
    [gridView addsubView:[self createButtonAtRow:row col:col]];
  }
}
[myView addSubview:gridView];
[gridView release];  // Let myView retain gridView.
Run Code Online (Sandbox Code Playgroud)