[英]How do I perform an action on a subclassed UIView when tapped?
I have subclassed UIView
and I want to be able to set a stroke colour around the view when it is tapped. 我已经将
UIView
子类化,并且希望能够在点击视图时在视图周围设置笔触颜色。
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: 我还实现了
highlightSquare
方法,如下所示:
-(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. 这
CJGGameSquare
背景设置为红色,但是我想改为设置笔触颜色或CJGGameSquare
对象唯一的其他一些值。
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. 然后,您可以识别出何时相应地触摸了
UIView
的绘制。
You could draw a border to view's layer or you could draw a rectangular path in the drawRect:(NSRect *)
of your subclass. 您可以绘制边框以查看图层,也可以在子类的
drawRect:(NSRect *)
中绘制矩形路径。
For example: 例如:
#import <QuartzCore/QuartzCore.h>
view.layer.borderColor = [UIColor greenColor].CGColor;
view.layer.borderWidth = 5.0f;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.