Using layoutsubviews() works properly when cycling through UIButtons, but not when cycling while retrieving them by tag

StackOverflow https://stackoverflow.com/questions/4659788

Pergunta

I'm trying to mimic the iPhone Springboard drag and drop functionality for a tile game and am currently using MatrixCells to generate UIButtons in the View initalisation and add them to the view. The MatrixCells have an order tag, which is used for their own button as well ([button setTag:[cell order]];).

When using `layoutSubviews' to cycle through the UIButtons in the view to arrange them in a grid, it works fine. The grid pops up and my dragging functionality allows me to free-drag the buttons where I will.

- (void)layoutSubviews {

int row = 0;
int col = 0;
for ( UIButton *button in [self subviews] ) {
    [button setFrame:CGRectMake( col * 80 + 5, row * 80 + 25, 70, 70)];

    if (col < 3) {
        col++;
    }
    else {
        row++;
        col = 0;
    }
}

}

However, cycling through subviews doesn't work when changing the order of the cells, since I'm pretty sure I'm not supposed to mess around in there at all. So, I wanted to cycle through my MatrixCells and use their order to get the appropriate view and then change the frame. However, the layout gets messed up at button 0 and I can't use them as buttons anymore.

- (void)layoutSubviews {

int row = 0;
int col = 0;
for (MatrixCell *cell in currentOrder) {
    UIView *view = [self viewWithTag:[cell order]];
    [view setFrame:CGRectMake( col * 80 + 5, row * 80 + 25, 70, 70 )];
    if (col < 3) {
        col++;
    }
    else {
        row++;
        col = 0;
    }
}

}

Here is a picture with the results: http://i52.tinypic.com/2q903lk.png

viewWithTag seemed the be the most elegant solution for this. So I'm at a loss. Any idea why these implementations don't render the same?

Foi útil?

Solução 2

[self viewWithTag:0] returns self first, instead of the expected (UIButton *), since I didn't change the view's tag upon initialization. Apparantly tags default to 0 at initialization. layoutsubviews then proceeded to change the frame of self, messing up the layout and functionality. I solved this dilemma by changing the view's tag to 999 at initialization.

Outras dicas

It looks to me rather like you have a background UIImage to provide that grey gradient backdrop. It also looks like your button 0 might have a [cell order] of 0. I'm going to guess that you've never changed the tag of your background UIImage, which will thus default to 0.

When you call [self viewWithTag] for the first UIButton (labeled 0), it will find the first subview with a tag 0 - the background image, not the UIButton you expected - and move that. This, I suspect. is why all the other buttons line up fine, why the background moves oddly, and why your 0 button is not visible.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top