【问题标题】:How to pass on string parameter to another method through button selector?如何通过按钮选择器将字符串参数传递给另一个方法?
【发布时间】:2016-09-22 16:20:42
【问题描述】:

我有下面这个接收 stickerURLString 作为输入的委托方法:

- (void)selectedSticker:(NSString *)stickerURLString {
    //...
        [self.stickerPreviewButton addTarget:self action:@selector(sendStickerPreviewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    //...
}

并且选择器调用这个方法sendStickerPreviewButtonPressed

- (void)sendStickerPreviewButtonPressed: (NSString *)stickerURLString {
    [self.delegate InputFunctionView:self sendSticker:stickerURLString];
}

如您所见,为了使这项工作按预期进行,我必须将 stickerURLStringselectedSticker 方法传递给 sendStickerPreviewButtonPressed。 p>

我试过这个:

[self.stickerPreviewButton performSelector:@selector(sendStickerPreviewButtonPressed:) withObject:stickerURLString];

而不是这个:

[self.stickerPreviewButton addTarget:self action:@selector(sendStickerPreviewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

但我收到“以 NSException 类型的未捕获异常终止”错误。

那么有人知道如何通过按钮选择器将字符串参数传递给另一个方法吗?

【问题讨论】:

  • 声明一个全局变量并在你的方法中赋值。
  • @AnuradhS 是的,这似乎是我使用全局变量的方式,尽管我试图避免这种情况,因为我的代码非常复杂。谢谢!

标签: ios objective-c uibutton performselector


【解决方案1】:

如果你使用 performSelector 来调用函数,那么你可以使用这个变体

  • (id)performSelector:(SEL)aSelector withObject:(id)object;

文档

https://developer.apple.com/reference/objectivec/1418956-nsobject/1418764-performselector


您还可以查看这个答案,其中解释了另一种解决方案,在我看来可能更复杂但有用

https://stackoverflow.com/a/14161831/1502070

【讨论】:

    【解决方案2】:

    对于 UIControl 对象函数,第一个参数是 id 类型,由控件本身传递,你会在 sendStickerPreviewButtonPressed: function which is not convertible to string 中得到 uibutton 对象作为参数,所以你得到一个错误,你可以通过扩展 UIbutton 类传递字符串通过您的自定义课程。然后创建您自己的类的按钮,并为您获取自定义属性表单发送器按钮。

         -(void)sendStickerPreviewButtonPressed:(mycustomButton*)sender{
          //sender.myCustomString
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多