Question

I have subclassed UIView and I want to be able to set a stroke colour around the view when it is tapped.

At the moment I have added a gesture recogniser to the view in my View Controller like so:

    CJGGameSquare* gameSquare = [[CJGGameSquare alloc] initWithSquareSize:_squareSize andSquareNumber:i andSquareName:[squareNames objectAtIndex:i]];
    [_mainBoard addSubview:gameSquare];

    CGRect gameSquareFrame = {
        xPosition,
        yPosition,
        _squareSize,
        _squareSize
    };

    [gameSquare setFrame:gameSquareFrame];

UIGestureRecognizer* singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightSquare:)];
[gameSquare addGestureRecognizer:singleFingerTap];

I've also implemented the highlightSquare method as follows:

-(void)highlightSquare:(UITapGestureRecognizer *)sender;
{
    UIView* square = sender.view;
    square.backgroundColor = [UIColor redColor];
}

This sets the background to red but I want instead to set a stroke colour or some other values that are unique to my CJGGameSquare object.

Was it helpful?

Solution

If you already have a subclass override these methods:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

Then you can recognize when your UIView is touched an draw accordingly.

You could draw a border to view's layer or you could draw a rectangular path in the drawRect:(NSRect *) of your subclass.

For example:

#import <QuartzCore/QuartzCore.h>

view.layer.borderColor = [UIColor greenColor].CGColor;
view.layer.borderWidth = 5.0f;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top