开发者

multi UIView subclass create in loop

i create a UIView subclass that name is "GameCard"

and i also create xib file. and added one UIView.

so i want add each GameCard class to ivew in loopping

so I wrote this codes.

- (void)viewDidLoad {
    NSArray *nibViews =  [[NSBundle mainBu开发者_开发技巧ndle] loadNibNamed:@"GameCard" owner:self options:nil];
    GameCard *aGameCard = [nibViews objectAtIndex:0];
    for (int i = 0; i < [gameWordData1 count]; i++) {
        int x = i / 3;
        int y = i % 3;
        GameCard *bGameCard = [aGameCard copy];
        bGameCard.frame = CGRectMake((10 + y * 100), (x * 70), 100, 70);
        [self.view addSubview:bGameCard];
    }
}

so I saw just one GameCard class in view

so I try this code

- (void)viewDidLoad {
for (int i = 0; i < [gameWordData1 count]; i++) {
    int x = i / 3;
    int y = i % 3;
    CGRect rect = CGRectMake((10 + y * 100), (x * 70), 100, 70);
    GameCard *aGameCard = [[GameCard alloc] initWithFrame:rect];
    [self.view addSubview:aGameCard];
    NSLog(@"%i", [[self.view subviews] count]);
}
}

I saw anythins in view. but it seems GameCard class is created.

what's wrong my code.

sorry about my english :)


I would suggest loading the nib file for each view. To make speed up the process, you can use UINib instead of NSBundle to load the data.

- (void)viewDidLoad {
    UINib *nib = [UINib nibWithNibName:@"GameCard" bundle:nil];
    for(int i = 0; i < [gameWordData1 count]; i++) {
        int x = i / 3;
        int y = i % 3;
        NSArray *nibViews = [nib instantiateWithOwner:self options:nil];
        GameCard *aGameCard = [nibViews objectAtIndex:0];
        aGameCard.frame = CGRectMake((10+y*100),(x*70),100,70);
        [self.view addSubview:aGameCard];
    }
}

PS: As @jamihash noted in the comments, you may have accidentally switched x and y in CGRectMake. I used it the way you had it in your code, but check it before you use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜