通过代码在iPhone屏幕上显示对象

时间:2012-06-30 03:49:37

标签: iphone

这是我关于Stack Overflow的第一个问题,所以我希望我足够清楚。

我正在为iPhone设计游戏,但在显示某些对象时遇到问题。我有一个NSMutableArray对象(一个自定义对象类,它是UIImageView的子类),我希望能够在屏幕上显示它们。但是,数组可以更改大小,因此我无法直接链接接口构建器中的每个元素。有没有人知道如何开始解决这个问题?

谢谢!

守则:

//This code is in the viewController.m file
//The main array of objects is nodeList. Each node subclasses UIImageView.
//nodeList was also synthesized at the beginning of the file with @synthesize.


//initialize array
nodeList= [[NSMutableArray alloc] initWithCapacity:(vertLinks*horizLinks)];

//make center node
Node *n = [Node alloc];

//Initialize the node (just puts an x and y position in, and gives it a mass)
[n nodeInit:(startX):(startY):(nodeMass)];
[nodeList addObject:(n)];

//creates a 'web' of nodes, and adds each one to the array
for (int i = 1; i < vertLinks; i++)
{
    for (int j = 0; j < horizLinks; j++)
    {
        //draw the line to each point
        int nodeX = (startX + cos(((360 / horizLinks) * j) * (M_PI / 180)) * rad * i);
        int nodeY = (startY + sin(((360 / horizLinks) * j) * (M_PI / 180)) * rad * i);

        //add it to the screen
        Node *nd = [Node alloc];

        [nd nodeInit:(nodeX):(nodeY):(nodeMass)];

        if (i == vertLinks - 1)
        {
            nd.solid = true;
        }

        [nodeList addObject:(nd)];
    }
}

1 个答案:

答案 0 :(得分:0)

有点难以准确回答,但基本上你需要遍历数组中的对象,并分别添加每个对象。如果这些对象是UIView,UIImageView或UIButton等视图,那么你可以这样做:

for (int i=0; i<array.count; i++) {
   UIView *thisView = [array objectAtIndex:i];
   [self.view addSubview:thisView]
}

如果它们是字符串或数字或其他东西,那么您需要创建标签或文本字段或其他东西来显示对象。

for (int i=0; i<array.count; i++) {
   NSString *string = [array objectAtIndex:i];
   UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100*i, 100, 100)];
   [label setTitle:string];
   [self.view addSubview:label]
}

你所谈论的对象类型真的很重要。如果您需要任何真正的帮助,您需要告诉我们这些图像是什么类型。这也是发布的正确方式。

请发布更多详情,我很乐意继续回答。