创建一个UIViews数组

时间:2014-03-29 01:45:34

标签: ios objective-c uiview

我难以在我的代码中创建一个UIViews数组。我创建了一个棋盘,每个方块都是UIView。在我的UIViewController类声明中,我有以下内容 -

@interface ChessViewController : UIViewController
{
    ChessSquareView   *squares[64];
}

在.m文件中,我正在为这个for循环中的每个64个方块创建视图 -

for ( int i=0; i<64; i++)
    squares[i] = [ [ChessSquareView alloc] initWithFrame:sq];

其中sq是该广场的位置和尺寸(CGRect)。在ChessSquareView.m文件中,我将CGRect存储在变量中。我在initWithFrame函数中打印它们以确保我添加正确的值。

稍后在代码中(例如touchEnded函数)我循环遍历视图数组并发现对象都是错误的。创建UIViews数组的正确方法是什么?

编辑:

为了澄清touchEnded功能,我循环浏览视图以找出用户点击的位置。在该函数中,我使用frame函数打印出每个视图的NSStringFromCGRect,但它们都是错误的。

for (int i=0; i<25; i++)
{
    NSLog(@"Checking Square %@", NSStringFromCGRect([squares[i] frame]));

}

2 个答案:

答案 0 :(得分:0)

在.h:

@property (nonatomic, strong) NSMutableArray *squares;

在.m

self.squares = [[NSMutableArray alloc] init];

for(int i = 0; i < 64; i++)
{
    ChessSquareView *v = [[ChessSquareView alloc] initWithFrame:sq];
    [self.squares addObject:v];
}

答案 1 :(得分:0)

与其他人一样,我建议使用NSMutableArray而不是C数组。即使如此,C数组应该可以工作。

但是,您发布的代码对每个视图的帧使用相同的值。他们都应该重叠。 (除非你遗漏了计算sq矩形的代码?如果你这样做了,那就显示一下代码,因为找出问题无疑是重要的。)

为什么不使用i为每个视图分配标签?那会帮助你看看这些观点是否会以某种方式被扰乱。