【问题标题】:question about selectors关于选择器的问题
【发布时间】:2011-10-12 07:45:01
【问题描述】:

我有以下几点:

  UITapGestureRecognizer *tapGesture;
    SEL sel = @selector(profilePop:withUser:) withObject:tapGesture withObject:message.creator;
    tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:sel];

我希望它能够调用:

- (void)profilePop:(UITapGestureRecognizer *)recognizer withUser:(Login *)user
{
    //some code here
}

但为什么不这样做呢?

【问题讨论】:

  • profilePop:withUser: 在自己的界面吗?
  • 处理程序希望如何接收(Login *)user 参数?
  • 我已经编辑了上面的代码,很抱歉,现在它给了我一个错误,sel 需要一个']'?
  • 那我该如何改变它
  • 那我该如何定义传入参数参数的对象呢?

标签: iphone objective-c ipad


【解决方案1】:

the documentation 中所述,操作消息必须采用特定形式

- (void)handleGesture
- (void)handleGesture:(UIGestureRecognizer *)sender

您不能只使用任意选择器作为操作;它必须是符合上述模式之一的选择器。

【讨论】:

  • 如果我想将一个对象传递给那个手势识别器,那么合适的方法是什么?
  • 传递给手势识别器的动作不是识别器中的方法,而是识别器目标中的方法。当识别器确定其手势已被执行时,它将动作消息发送到其目标。此外,您正在使用 UITapGestureRecognizer,它无法访问对象,并且不知道如何处理该对象。所以,我已经告诉过你为什么你的方法没有被调用作为点击识别器的动作。也许您可以花一些时间来澄清您的问题并解释您真正想要完成的工作?
【解决方案2】:

选择器只知道它的名称和任何参数名称,而不知道它的参数。

UIGestureRecognizer 仅接受其类型为 0 或 1 个参数的操作。

为了做你想做的事,你需要编写一个包装方法来将Login 实例传递给profilePop:withUser:

所以,你会这样写:

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(profilePopWrapper:)];
[[self view] addGestureRecognizer:tapGesture];
[tapGesture release];


//....

- (void) profilePopWrapper:(UIGestureRecognizer *) gr {
    Login *someUser = ...;
    [self profilePop:gr withUser:someUser];
}

【讨论】:

  • 问题是 Login* 可以在我设置 tapgesturerecognizer 的那个函数中被提取出来
  • @adit 为什么不能将其存储在实例变量中?
【解决方案3】:

以这种方式在@selector 函数中使用单个参数。

 UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(profilePop:)];

因为 UITapGestureRecognizer 只能识别点击识别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    相关资源
    最近更新 更多