【问题标题】:UIview custom class including a tapgesture is it possible?UIview 自定义类包括一个 Tapgesture 是可能的吗?
【发布时间】:2017-02-12 05:08:11
【问题描述】:

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

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

.m 文件

- (id)initWithFrame:(CGRect)frame myParams:(NSArray*)params{ self = [super initWithFrame:frame]; 如果(自我){ UIView *view = [UIView alloc] initWithFrame:CGRectMake(0,0,100,100)]; //尝试发送带有手势的uiview include view.userInteractionEnabled = YES; UITapGestureRecognizer *tap = [UITapGestureRecognizer alloc] initWithTarget:self action:@selector(test)]; [查看 addGestureRecognizer:tap]; [自我添加子视图:视图]; } 回归自我; }

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

自定义 *view = [自定义分配] initWithFrame:self.view.bounds myParams:array]; [self.view addSubview:view];

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

.h 文件

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

.m 文件

+ (UIView *)viewWithParams:(NSArray*)params{ UIView *view = [UIView alloc] initWithFrame:CGRectMake(0,0,100,100)]; NSLog(@"读取参数%@", params); //尝试发送带有手势的uiview include view.userInteractionEnabled = YES; UITapGestureRecognizer *tap = [UITapGestureRecognizer alloc] initWithTarget:self action:@selector(test)]; [查看 addGestureRecognizer:tap]; 返回视图; } -(无效)测试{ NSLog('它有效...'); }

更新:因为实例方法正在工作。但是作为类方法我不能让它工作。有人知道可能吗?

【问题讨论】:

  • 你可以试试给 self.view.userInteractionEnabled = YES;在视图控制器中?
  • 这没有尝试作为类方法。

标签: ios objective-c uiview uitapgesturerecognizer


【解决方案1】:

第一部分

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

第二部分

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

【讨论】:

    【解决方案2】:

    View 将在触发 initwithcoder 后添加,只需在 init with coder 中使用此代码 ...

       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 最大时间间隔

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多