首页 > 解决方案 > 在 UIView(子类)而不是父 UIViewController 中监听方法(touchesBegan、touchesMoved、touchesEnded)?

问题描述

我是 iOS 开发的新手。

我正在尝试创建一个涂鸦应用程序,我没有使用故事板。我的代码是这样的:

在我的UIView中,声明了这些方法(我认为是要覆盖),并且我有在那里绘制涂鸦的代码(我在 UIViewController 上做了一个小演示并工作)。

当我触摸屏幕时,可以看到所有这些日志,但没有调用子视图上的方法。

我尝试创建一个“侦听” VWdashboard上的方法并将数据传递给我UIView的 Doodle 的委托,以便将在相应的 doodleUIImageView等中绘制涂鸦,但不起作用:

VW仪表板.h

    @class Doodle;
    @protocol DoodleDelegate <NSObject>

    - (void)touchBegan:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchMoved:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchEnded:(NSSet *)touches withEvent:(UIEvent *)event;

    @end

    @interface VWDashboard : VWBase {
        id <DoodleDelegate> delegate;
    }

    @property (retain, nonatomic) id <DoodleDelegate> delegate;

    @end

涂鸦.h

    #import <UIKit/UIKit.h>
    #import "VWDashboard.h"

    NS_ASSUME_NONNULL_BEGIN

    @interface Doodle : UIView <DoodleDelegate> {

        // Drawing
        CGPoint lastPoint;
        CGFloat red;
        CGFloat green;
        CGFloat blue;
        CGFloat brush;
        CGFloat opacity;
        BOOL mouseSwiped;
    }

    @end

    NS_ASSUME_NONNULL_END

涂鸦.m

    #import "Doodle.h"
    #import "SCLAlertView.h"

    @implementation Doodle {

        UIImageView *canvasSignature, *canvasDoodle;
    }

    - (id)initWithFrame:(CGRect)frame {

    /// renderUI ....

        return self;
    }

    -(void) renderUI...

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

    // Drawing code

    }
    - (void)touchMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        // Drawing code
    }
    - (void)touchEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // Drawing code
    }

    @end

这就是我在VWdashboard中设置委托的方式:

    Doodle *doodl = [[Doodle alloc] initWithFrame: _moduleLayoutActive.bounds];
    [self setDoodleDelegate:doodl];
    [_moduleLayoutActive addSubview: doodl];

请!任何帮助我都会非常感激,谢谢!

标签: iosobjective-cxcodedelegatesuikit

解决方案


这是你可以做的......

(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch= [touches anyObject];
    if ([touch view] == yourView)
    {
        //your code
    }

}

(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch= [touches anyObject];
    if ([touch view] == yourView)
    {
        //your code
    }

}

(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch= [touches anyObject];
    if ([touch view] == yourView)
    {
        //your code
    }

}

希望这可以帮助。


推荐阅读