Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending anonymous actions using UIApplication.sharedApplication().sendAction in Swift 3

I have been using sendAction method with nil target to communicate actions from Cells(UITableViewCell/UICollectionViewCell) to ViewControllers, instead of implementing a delegate.

Since Swift 2.2 the syntax for selector has been updated and I get some warning. The new #selector syntax insists on specifying the selectorname followed by classname. If I mention the class name then there is no meaning in setting the target to nil.

Any workaround for this?

    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");
    }
}
like image 789
AUK4SO Avatar asked Oct 21 '25 09:10

AUK4SO


1 Answers

You can use Selector() to create a selector from a string in Objective-C style. To avoid a warning saying "Use #selector", use a parameter to store the selector name and pass it to Selector() instead of passing a string literal directly.

let selectorName = "updateCartWithTotalAmountPayableWithDiscount:"
UIApplication.sharedApplication().sendAction(Selector(selectorName), to: nil, from: self, forEvent: nil)
like image 50
Yoichi Tagaya Avatar answered Oct 24 '25 00:10

Yoichi Tagaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!