首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在UIView子类中创建对象网格?

如何在UIView子类中创建对象网格?
EN

Stack Overflow用户
提问于 2012-04-13 08:47:26
回答 1查看 1.1K关注 0票数 0

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

代码语言:javascript
复制
- (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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-13 10:27:10

使用UIViews会让你的工作变得更轻松。

这里有一个网格例程-它可以写得更紧凑,但它更容易理解,因为有很多显式声明的变量。将其放入您的主ViewController中并在ViewWillAppear中调用它。

代码语言:javascript
复制
- (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;

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10133881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档