joshft91
joshft91

Reputation: 1895

Disabling certain UIViews from touches

I have a class called TileView which extends UIView. In another view I create 9 TileView objects and display them on the screen. Below is an example of 1 of them

tile1 = [[TileView alloc]
             initWithFrame:CGRectMake(20,20, 100, 150)
             withImageNamed:@"tile1.png"
             value: 1
             isTileFlipped: NO];

A user can touch any of the tiles. When a tile is touched it is "turned over" - the image is named to a plain brown tile and isTileFlipped is set to 'YES'. Now comes the part I'm stuck on: There is a confirm button.

When the confirm button is pressed, it takes all the tiles that are flipped and adds them to an array called acceptedTiles. After confirm is pressed I need to make sure that the tiles in acceptedTiles cannot be pressed or interacted with. I am at a loss as to what would be the best way to do this. Here is touchesBegan so you can get an idea of what is happening.

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

int currentTileCount = [(BoxView *)self.superview getTileCount];
int currentTileValue = [self getTileValue];
int tilecount;

if (!isFlipped) {
    [image setImage:[UIImage imageNamed:@"tileflipped.png"]];
    isFlipped = YES;
    tilecount = currentTileCount + currentTileValue;
    [(BoxView *)self.superview setTileCount:tilecount];
    [(BoxView *)self.superview addToArray:self index:currentTileValue-1];
}

else {
    [image setImage:[UIImage imageNamed:imageNamed]];
    isFlipped = NO;
    tilecount = currentTileCount - (int)currentTileValue;
    [(BoxView *)self.superview setTileCount:tilecount];
    [(BoxView *)self.superview removeFromArray: currentTileValue-1];
}
}

Upvotes: 0

Views: 51

Answers (2)

Steven Fisher
Steven Fisher

Reputation: 44886

If all you want is the tiles not to be interacted with, surely simply:

for (UIView *tile in acceptedTiles) {
    [tile setUserInteractionEnabled:NO];
}

If that doesn't meet your requirements, please elaborate. It seems perfect for you.

Upvotes: 1

Adam Schlag
Adam Schlag

Reputation: 36

If you didn't want to change your code too much you could check if the view was added to acceptedTiles before you do anything else in touchesBegan:withEvent, and if it was just return.

However, I wonder why you aren't using a UITapGestureRecognizer here instead? If you did you could set a delegate that implemented the gestureRecognizerShouldBegin: method where you could check if the view was in acceptedTiles there instead of mixing it in with your other tap recognition logic.

Upvotes: 0

Related Questions