首页 文章

UIview自定义类包括tapgesture有可能吗?

提问于
浏览
0

我试图使用 initWithFrame 但我无法显示 UIView ,这种代码解决了我在这里看到的许多问题,但不是我的情况:

- (id)initWithFrame:(CGRect)frame myParams:(NSArray*)params;

.m file

- (id)initWithFrame:(CGRect)frame myParams:(NSArray*)params{
      self = [super initWithFrame:frame];
      if(self){
        UIView *view = [UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
        //Trying to send an uiview with gesture include
        view.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [UITapGestureRecognizer alloc] 
        initWithTarget:self action:@selector(test)];
        [view addGestureRecognizer:tap];    
        [self addSubview:view];
      }
      return self;
    }

以下是我试图在 UIViewController 中添加视图的方法:也许在这里我做错了,对吧?

Custom *view = [Custom alloc] initWithFrame:self.view.bounds myParams:array];
      [self.view addSubview:view];

所以,我的问题是可以在这个类中生成的 UIView 中添加 UITapGesture ,因为它没有触发:

.h file

+ (UIView *)viewParams:(NSArray*)params;

.m file

+ (UIView *)viewWithParams:(NSArray*)params{
      UIView *view = [UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];

      NSLog(@"read params %@", params);

      //Trying to send an uiview with gesture include
      view.userInteractionEnabled = YES;
      UITapGestureRecognizer *tap = [UITapGestureRecognizer alloc] 
      initWithTarget:self action:@selector(test)];
      [view addGestureRecognizer:tap];

      return view;
    }
    - (void)test{
      NSLog('it works...');
    }

UPDATE : As instance method is working. But as class method I can not make it work. somebody know if possible?

2 回答

  • 0

    1st Part

    如果您使用 XIB 作为customView,则需要使用 awakeFromNib 方法 . 但是,如果您只是尝试通过代码创建,那么只需使用 initWithFrame: 方法并在初始化程序中添加手势识别器 .

    2nd Part

    对于触发轻击手势识别器,您正在添加识别器目标 self ,即您的 customView . 因此,事件将在您的customViewClass类中触发,然后才能在控制器中获取这些事件,您需要使用协议和委托 . 并将customView的委托设置为您要在控制器中使用的任何控制器 .

  • 0

    视图将在触发initwithcoder后添加,只需在init中使用此代码与编码器...

    dispatch_after(0.1, dispatch_get_main_queue(), ^(void)
               {
                   UIView *view = [UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
                //Trying to send an uiview with gesture include
                view.userInteractionEnabled = YES;
                UITapGestureRecognizer *tap = [UITapGestureRecognizer alloc] 
                initWithTarget:self action:@selector(test)];
                [view addGestureRecognizer:tap];    
                [self addSubview:view];
               });
     }
          return self;
        }
    

    最小时间间隔0.1根据数据加载要求设置的最大时间间隔

相关问题