在 Swift 3 中使用 UIApplication.sharedApplication().sendAction 发送匿名操作

AUK*_*4SO 3 objective-c ios swift swift2

我一直在使用sendAction方法 with来传达来自to 的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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Yoi*_*aya 5

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

let selectorName = "updateCartWithTotalAmountPayableWithDiscount:"
UIApplication.sharedApplication().sendAction(Selector(selectorName), to: nil, from: self, forEvent: nil)
Run Code Online (Sandbox Code Playgroud)