代码之家  ›  专栏  ›  技术社区  ›  James Skidmore

构建10x10 uibuttons网格的最佳方法?

  •  6
  • James Skidmore  · 技术社区  · 16 年前

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

    我的问题: 创建此网格最简单的方法是什么?以编程方式还是通过接口生成器?如果以编程方式访问这些按钮,最简单的方法是什么,以便在触摸它们时, 我能知道触摸按钮的行和列号吗?

    2 回复  |  直到 16 年前
        1
  •  13
  •   squelart    16 年前

    我个人不喜欢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;
        // ...
    }
    
        2
  •  8
  •   Tyler    16 年前

    您可以使用 moriarty library 帮助 布局 -把每个按钮放在你想要的地方。部分建立在squelart的示例代码上,作为createButtonAtrow:col:method,其工作方式如下:

    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.