点击时如何对子类UIView执行操作?

时间:2014-01-03 14:08:43

标签: ios uiview uigesturerecognizer subclass uitapgesturerecognizer

我已经将UIView子类化了,我希望能够在点击时在视图周围设置描边颜色。

目前我在视图控制器中为视图添加了一个手势识别器,如下所示:

    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];

我还实现了highlightSquare方法,如下所示:

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

这会将背景设置为红色,但我想要设置一个笔触颜色或其他一些我CJGGameSquare对象独有的值。

1 个答案:

答案 0 :(得分:1)

如果您已经有子类覆盖这些方法:

- (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

然后,您可以识别出UIView相应地触及平局。

您可以绘制边框以查看图层,也可以在子类的drawRect:(NSRect *)中绘制矩形路径。

例如:

#import <QuartzCore/QuartzCore.h>

view.layer.borderColor = [UIColor greenColor].CGColor;
view.layer.borderWidth = 5.0f;