I am trying to understand how the sender value works in segues.
In some places in my code both works:
performSegueWithIdentifier("mySegue", sender: self)
performSegueWithIdentifier("mySegue", sender: sender)
But what is the difference between having self / sender?
As @iosDev82 says in his answer, sender is an optional that names the object (if any) that triggered the segue.
If you trigger a segue through code in a view controller, you could pass the view controller (self), or you could pass nil. It's just a piece of information that is passed along to prepareForSegue (again as iOSDv82 says.)
If you trigger a segue in the code of an IBAction method, your IBAction may have it's own sender parameter (frequently a button.) In that case you can pass along the sender parameter to the performSegueWithIdentifier
method.
Example:
@IBAction func buttonAction(sender: UIButton)
{
//In this case the button IBAction takes a pointer to the button as a param.
//Pass it on to the segue in case performWithSegue needs it.
self.performSegueWithIdentifier("someID", sender: sender)
}
sender
is just an argument that gets passed along with this function.
This is received later in the function prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
, where you can get this object and make decision based on who the sender is.
As an Example, suppose you want to edit something at an IndexPath . You call
performSegue(withIdentifier: "showItem", sender: indexPath)
from wherever you want ( indexPath is of type IndexPath here).
Then, inside the prepare(segue:sender:)
, you do:
...
switch segue.identifier {
case "showItem"?:
// Figure out which row was just tapped
if let row = tableView.indexPathForSelectedRow?.row {
editRow(segue, row)
} else {
let selectedIndexPath = sender as! IndexPath
editRow(segue, selectedIndexPath.row)
}
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.