【问题标题】:Sending anonymous actions using UIApplication.sharedApplication().sendAction in Swift 3在 Swift 3 中使用 UIApplication.sharedApplication().sendAction 发送匿名操作
【发布时间】:2016-05-04 07:37:13
【问题描述】:

我一直在使用sendAction 方法和nil target 将操作从Cells(UITableViewCell/UICollectionViewCell) 传递到ViewControllers,而不是实现委托。

从 Swift 2.2 开始,选择器的语法已经更新,我收到了一些警告。新的#selector 语法坚持指定selectorname 后跟classname。如果我提到类名,那么将目标设置为 nil 没有任何意义。

有什么解决方法吗?

    class RedeemCell: UICollectionViewCell { 
    @IBAction func redeemAction(sender: AnyObject) {                 
      UIApplication.sharedApplication().sendAction("updateCartWithTotalAmountPayableWithDiscount:", to: nil, from: self, forEvent: nil)
        } 
    }

class CartVC: UIViewController {

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell: UICollectionViewCell?

            cell = collectionView.dequeueReusableCellWithReuseIdentifier("redeempoints", forIndexPath: indexPath)


        return cell!;
    }

func updateCartWithTotalAmountPayableWithDiscount(sender: AnyObject) {
        print("this will be called as the action movies through responderchain and encounters this method");
    }
}

【问题讨论】:

  • 你能分享一下代码来解释你到目前为止是如何使用它的吗?
  • @rptwsthi 用代码更新了问题
  • 是的,我刚刚检查过了,不幸的是我没有解决方法。可能有人来救援。祝你好运。

标签: ios objective-c swift swift2.2


【解决方案1】:

您可以使用Selector() 从Objective-C 风格的字符串创建选择器。为避免出现“使用 #selector”的警告,请使用参数存储选择器名称并将其传递给 Selector(),而不是直接传递字符串文字。

let selectorName = "updateCartWithTotalAmountPayableWithDiscount:"
UIApplication.sharedApplication().sendAction(Selector(selectorName), to: nil, from: self, forEvent: nil)

【讨论】:

  • 或者你可以在字符串周围加上一个额外的括号:Selector(("updateCartWithTotalAmountPayableWithDiscount:"))
【解决方案2】:

您可以(并且可能应该)通过#selector(CartVC.updateCartWithTotalAmountPayableWithDiscount)。当你这样做时,你是说你想要一个updateCart... 函数的选择器,该函数由CartVC 类定义——而不是由其他类定义的updateCart... 函数。

这与将nil 作为目标传递的含义不同——你在#selector 表达式中命名的类根据你想要发送的类来阐明什么定义它。目标是关于您将消息发送给。当您为目标选择 nil 时,您的意思是消息应该发送到可以处理它的第一个对象——这可能是 CartVC 的多个实例之一,或者是另一个接受相同消息的类的实例。

【讨论】:

    【解决方案3】:

    你为什么使用sendAction,而不是使用NSNotificationCenter之类的东西?

    【讨论】:

    • 如果 sendAction 无法达到要求,我可以使用委托或 NSNotificationCenter。我的疑问是,使用新语法,我们将永远无法像上面那样使用 sendAction。
    • 鉴于它不像您在上面使用 sendAction 所做的那样工作,也许现在是时候重新考虑您过去的决定并改用正确的处理方式了?
    • NSNotificationCenter 用于在层次结构中向下广播事件。 sendAction(和委托)用于将事件向上发送。
    【解决方案4】:

    这有点太晚了,但现在您应该定义一个对 Objective-c 运行时可见的协议并使用该协议。我猜 UITableViewDelegate 现在看起来更漂亮了,不是吗? :)

    【讨论】:

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