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

时间:2016-10-04 06:23:12

标签: ios objective-c uiview uitapgesturerecognizer

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

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

.m文件


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

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

.h文件


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

.m文件


    + (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...');
    }

更新:实例方法正在运行。但作为阶级方法,我无法使其发挥作用。有人知道可能吗?

2 个答案:

答案 0 :(得分:0)

第一部分

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

第二部分

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

答案 1 :(得分: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最大时间间隔

相关问题