Best way to build 10x10 grid of UIButtons?

后端 未结 2 924
深忆病人
深忆病人 2021-02-02 04:28

I\'m going to have a 10x10 grid of UIButton objects. Each of these UIButtons is going to need to be referenced by the row and column number, so they should probably be stored in

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 04:38

    I personally don't like IB, so I recommend to do it programmatically!

    Use an NSArray to store your UIButton's. Each button's index is row*COLUMNS+column.

    Set the tag property to BASE+index (BASE being an arbitrary value > 0) so that you can find a button's position: 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;
        // ...
    }
    

提交回复
热议问题