コールバック関数(クロージャ)を使用した値渡しのサンプルを作成してみた
クロージャー、コールバック関数について理解を深めるためにサンプルを作ってみました。
この書き方があっているのか分かりませんが、とりあえず動いたので。
FirstViewController.swift
import UIKit
class FirstViewController: UIViewController {
@IBOutlet weak var label: UILabel!{
didSet{
label.text = "0"
}
}
@IBAction func nextButton(_ sender: UIButton) {
let secondStoryboard = UIStoryboard(name: "Second", bundle: nil)
let secondVC = secondStoryboard.instantiateInitialViewController() as!SecondViewController
secondVC.completion = { CountModel in
print("ーーーー渡されたよーーーーーーー")
self.label.text = CountModel.count.description
}
let nav = self.navigationController!
nav.pushViewController(secondVC, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController{
private var countmodel = CountModel.init(count: 0)
var completion:((CountModel)->Void)?
@IBOutlet weak var countLabel: UILabel!{
didSet{
countLabel.text = countmodel.count.description
}
}
@IBAction func countButtun(_ sender: UIButton) {
countmodel.count = countmodel.count + 1
countLabel.text = countmodel.count.description
print(countmodel)
}
@IBAction func addButton(_ sender: Any) {
tap()
self.navigationController?.popViewController(animated: true)
}
//クロージャー関数
func tap(){
print("tapしたよ")
print(countmodel)
completion?(countmodel)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
CountModel.swift
import Foundation
struct CountModel {
var count:Int
}
Author And Source
この問題について(コールバック関数(クロージャ)を使用した値渡しのサンプルを作成してみた), 我々は、より多くの情報をここで見つけました https://qiita.com/taro-ken/items/2670d6c9e3b3e51b29f4著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .