0

截至目前,我的 view.m 文件中有一个 for 循环,在 drawRect 方法中。我有 for 循环在 x 轴上显示图像。我想做的是能够不仅在 x 轴上而且在 y 轴上制作图像网格。换句话说,你的典型网格。我还想让网格中的每个重复图像成为一个对象,并附加一些属性,例如布尔值、触摸时我可以检索它的 id 以及它的坐标。我将如何在objective-c中执行此操作?这是我到目前为止所拥有的,并不多:

- (void)drawRect:(CGRect)rect
{
    int intX = 0; 
    int intCounter = 0;
    int intY = 0;
    for (intCounter = 0; intCounter < 10; intCounter++) {
        UIImage* pngLeaf = [UIImage imageNamed:@"leaf2.png"];
        CGRect imgRectDefault = CGRectMake(intX, 0, 34, 34);
        [pngLeaf drawInRect:imgRectDefault];
        intX += 32;
        intY += 32;
    }
}
4

1 回答 1

1

使用 UIViews 会更轻松。

这是一个网格例程 - 它可以写得更紧凑,但通过显式声明的大量变量更容易理解。把它放在你的主 ViewController 中并在 ViewWillAppear 中调用它。

- (void)makeGrid
{


int xStart = 0;
int yStart = 0;
int xCurrent = xStart;
int yCurrent = yStart;

UIImage * myImage = [UIImage imageNamed:@"juicy-tomato_small.png"];

int xStepSize = myImage.size.width;
int yStepSize = myImage.size.height;

int xCnt = 8;
int yCnt = 8;

int cellCounter = 0;

UIView * gridContainerView = [[UIView alloc] init];
[self.view addSubview:gridContainerView];

for (int y = 0; y < yCnt; y++) {
    for (int x = 0; x < xCnt; x++) {
         printf("xCurrent %d  yCurrent %d \n", xCurrent, yCurrent);

        UIImageView * myView = [[UIImageView  alloc] initWithImage:myImage];
        CGRect rect = myView.frame;
        rect.origin.x = xCurrent;
        rect.origin.y = yCurrent;
        myView.frame = rect;
        myView.tag = cellCounter;
        [gridContainerView addSubview:myView];

        // just label stuff
        UILabel * myLabel = [[UILabel alloc] init];
        myLabel.textColor = [UIColor blackColor];
        myLabel.textAlignment = UITextAlignmentCenter;
        myLabel.frame = rect;
        myLabel.backgroundColor = [UIColor clearColor];
        myLabel.text = [NSString stringWithFormat:@"%d",cellCounter];
        [gridContainerView addSubview:myLabel];
        //--------------------------------

        xCurrent += xStepSize;
        cellCounter++;
    }

    xCurrent = xStart;
    yCurrent += yStepSize;
}

CGRect repositionRect = gridContainerView.frame;
repositionRect.origin.y = 100;
gridContainerView.frame = repositionRect;

}
于 2012-04-13T02:27:09.693 回答