建立10x10的UIButton网格的最佳方法? [英] Best way to build 10x10 grid of UIButtons?

查看:53
本文介绍了建立10x10的UIButton网格的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 some type of an array.

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

My question: what is the easiest way to create this grid? Programmatically or through the Interface Builder? If programmatically, what would be the easiest way to access these buttons so that when they are touched, I am able to know the row and column number of the touched button?

推荐答案

我个人不喜欢IB,因此建议您以编程方式进行操作!

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

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

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

将标签属性设置为BASE + index(BASE是任意值> 0),以便您可以找到按钮的位置:index=tag-BASE; row=index/COLUMNS; column=index%COLUMNS;

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;
    // ...
}

这篇关于建立10x10的UIButton网格的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆