Use closure to pass data between two controllers
You can try
class FirstView: UITableViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBAction func goToSecond(_ sender: UIButton) {
self.performSegue(withIdentifier: "segue1", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue1" {
let des = segue.destination as! SecondViewController
des.change = { [weak self] (value) in
print(value)
self?.titleLabel.text = "SetValue"// set a value
}
}
}
}
class SecondViewController: UIViewController {
var change : ((Bool) -> Void)?
@IBAction func pressChangeButton(_ sender: UIButton) {
change?(true)
}
}
How to pass closure as a variable?
Here's what I think you want to achieve:
class SomeView {
var buttonDidPressed: (() -> Void)? = nil {
didSet {
button.pressed = buttonDidPressed
}
}
let button = MyButton()
func press() {
button.press()
}
}
The reason your code isn't working is because in the SomeView.init
, buttonDidPressed
is nil
- i.e. it's a lack of reference. So:
buttonDidPressed = nil
button.pressed = buttonDidPressed
// is equivalent to
button.pressed = nil
Assigning a new (or different) reference to buttonDidPressed
later doesn't change the button.pressed
property.
How to pass a variable by value to an anonymous javascript function?
You need to create a new variable on each pass through the loop, so that it'll get captured in the closures you're creating for the event handlers.
However, merely moving the variable declaration into the loop won't accomplish this, because JavaScript doesn't introduce a new scope for arbitrary blocks.
One easy way to force the introduction of a new scope is to use another anonymous function:
for (var i=0;i<inlineRangeNavUrls.length;i++)
{
curDiv='#' + inlineRangeNavUrls[i][1];
if ($(curDiv).length)
{
(function(curTab)
{
$(curDiv).bind("mouseover", function(){showHideRangeSlidingTabs(curTab, true);} );
$(curDiv).bind("mouseout", function(){showHideRangeSlidingTabs(curTab, false);} );
})(inlineRangeNavUrls[i][0]); // pass as argument to anonymous function - this will introduce a new scope
}
}
As Jason suggests, you can actually clean this up quite a bit using jQuery's built-in hover()
function:
for (var i=0;i<inlineRangeNavUrls.length;i++)
{
(function(curTab) // introduce a new scope
{
$('#' + inlineRangeNavUrls[i][1])
.hover(
function(){showHideRangeSlidingTabs(curTab, true);},
function(){showHideRangeSlidingTabs(curTab, false);}
);
// establish per-loop variable by passsing as argument to anonymous function
})(inlineRangeNavUrls[i][0]);
}
Passing variable to closure
Your goal is to know how to supply a parameter to a closure. It's achieved with call_user_func_array.
Let's define a method in a class which accepts a closure.
class MyTestClass
{
public function doWork(callable $callback)
{
return call_user_func_array($callback, [$this]);
}
}
$obj = new MyTestClass();
$obj->doWork(function(MyTestClass $obj) {
//
});
Note: didn't test, but I take it that's what you were after?
passing parameter to closure function in javascript
Your MyLibrary.MyModule
itself is undefined
. This is because you're invoking an anonymous function with no return value to assign to it.
I assume you meant to do this instead:
MyLibrary.MyModule = function initialise(id, options) {
this.id = id;
this.c = document.getElementById(id);
this.ctx = this.c.getContext('2d');
this.properties = {
setup: {
backgroundColour: options.setup.backgroundColour || 'black'
},
scale: {
show: options.scale.show || true,
colour: options.scale.color || 'white'
},
}
console.log(properties.setup.baseFontSize);
};
Now you can do:
var inst = new MyLibrary.MyModule('c',options);
...and the 'c'
and options
will be received as arguments to the constructor.
If your purpose for the immediately invoked function expression was to close around some default value that the constructor could reference, then the IIFE would need to return a function that references that value.
How would I pass data using a closure?
Set class Tray like below
class Tray {
var cart: Items
var brandName: String
init(cart: Items,
brandName: String) {
self.cart = cart
self.brandName = brandName
}
}
In HomeViewController, under addActionHandler append selected items to cart
cell.addActionHandler = { (option: Int) in
print("Option selected = \(option)")
item.selectedOption = option
tray.append(Tray(cart: item, brandName: "<Brand Name>"))
}
Pass tray[] to CartViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? CartViewController {
vc.items = self.selectedItem
vc.tray = self.tray
}
}
In CartViewController, pass items to cartCell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = tray[indexPath.row]
cell.configure(withItems: cart.cart)
return cell
}
how to pass function in parameter using closure in swift 5
You first need to create an extension for UIViewController
instead of UIAlertController
Also, set the correct closure argument for the function and then call the function like this.
extension UIViewController {
func action(message: String, firstTitle: String, secondTitle: String, firstAction: (() -> Void)? = nil, secondAction: (() -> Void)? = nil) {
let actionSheet = UIAlertController(title: "", message: message, preferredStyle: .actionSheet)
let eButton = UIAlertAction(title: firstTitle ,
style: .default,
handler: {_ in firstAction?()})
let allEButton = UIAlertAction(title: secondTitle,
style: .default ,
handler: {_ in secondAction?()})
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel,
handler: nil)
[eButton, allEButton, cancelAction].forEach { $0.setValue(UIColor.red, forKey: "titleTextColor")}
actionSheet.addAction(eButton)
actionSheet.addAction(allEButton)
actionSheet.addAction(cancelAction)
present(actionSheet, animated: true, completion: nil)
}
}
Usage
private extension viewControllerA {
func alertBottomSheat() {
self.action(message: "Update", firstTitle: "Update only", secondTitle: "Update All", firstAction: saveEvent, secondAction: saveEvent)
}
@IBAction func deleteEventButtonClicked(_ sender: Any) {
self.action(message: "delete ", firstTitle: "Delete only", secondTitle: "Delete All ", firstAction: { self.deleteEvent()}, secondAction: { self.deleteEvent(deleteAll: true) })
}
func saveEvent() {
}
func deleteEvent(deleteAll: Bool = false) {
}
}
Note: Fixed coding standard rule and var names.
Pass a value to closure function in PHP
Did you try to use use
?
public function handle(UserFollowed $event)
{
$h = new \Acme\Helpers\functions();
$email = $h->getUserEmail($event->followed);
Mail::raw('Hi, welcome user!', function ($message) use ($email) {
$message->to($email)
->subject("New follower :)");
});
}
Swift: Escaping closure How to pass values to previous ViewController after success
You could add the dictionary to your success closure like this:
func addToCart(vc:UIViewController, param:[String:String], completionHandler:@escaping (_ success:Bool, _ errorC : Error?, _ stock_flag : Bool?, result: [String:Any]?) -> Void)
{ ... }
Afterwards you can just use it in the closure.
CartViewModel().addToCart(vc: self, param:params ) { (isDone, error, stock_flag, result) in
// Use result here
}
Related Topics
How to Write a Better Data Access Layer with Realm
Uialertview's Textfield Does Not Show Keyboard in iOS8
Google Signin: Unable to Disconnect iOS App
How to Use Sketch UI Elements Directly into Xcode
How to Compile Aws Customidentityprovider on Xcode 8 Beta 6
Translate Just 4 Lines of Code from Objective C to Swift (Pointers)
Error | [Ios] File Patterns: the 'Source_Files' Pattern Did Not Match Any File
Swift 4.2 Make Bottom of Tableview Move Up When Keyboard Shows
Can't Pan Image Taken from Camera with Uiimagepicker
Fetch() Doing Get Instead of Post on React-Native (iOS)
Xcode UI Test Uikeyinput Typetext
No Such Module 'Fbsdkcorekit' Xcode 7.4
Gkmatchmaker Invite Handler Deprecated
Will Download Resume After Closing My App in Background Mode
How to Request Photo Gallery Permissions in iOS a Second Time
Retina Display Vs Normal Display Color Difference
Invalid Transaction Receipt Returned by Appstorereceipturl (Nsdata), in iOS 7