【问题标题】:How do I perform an action on a subclassed UIView when tapped?点击时如何对子类 UIView 执行操作?
【发布时间】:2014-01-03 14:08:42
【问题描述】:

我对@9​​87654321@ 进行了子类化,并且我希望能够在点击视图时在视图周围设置笔触颜色。

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

    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 对象独有的一些其他值。

【问题讨论】:

    标签: ios uiview uigesturerecognizer subclass uitapgesturerecognizer


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多