前回、AppDelegateを使った方法をあげましたらアドバイスを頂き、実際に、シングルトンを使ってやってみました。
備忘録を含めた意味でも再投稿。
前回の記事
https://qiita.com/gurensouen/items/0f11c80c10afbc36653a
開発環境
Xcode 9.0
Swift 4.0
ボタンを押したら、「Label」と「View」が変わります。
ViewControllerには、「ViewController.swift」
nextViewControllerには、「nextViewController.swift」
コードは以下になります。
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var buttonOut: UIButton!
@IBOutlet weak var blackView: UIView!
let sin: Singl = Singl.sh
override func viewDidLoad() {
super.viewDidLoad()
sin.viewCon = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func butoon(_ sender: Any) {
sin.moji = "文字渡します"
sin.nextView?.mojichenge()
blackView.backgroundColor = UIColor.black
}
func redView(){
blackView.backgroundColor = UIColor.red
}
}
nextViewController.swift
import UIKit
class nextViewController: UIViewController {
@IBOutlet weak var label: UILabel!
let sin: Singl = Singl.sh
override func viewDidLoad() {
super.viewDidLoad()
sin.nextView = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func mojichenge(){
label.text = sin.moji
}
@IBAction func button(_ sender: Any) {
sin.viewCon?.redView()
label.text = "色変えます"
}
}
File.swift
import Foundation
class Singl {
var moji:String?
var viewCon:ViewController?
var nextView:nextViewController?
static let sh: Singl = Singl()
}
今回はこんな感じで仕上げました。
誰かの参考になったら幸いです。
ご指摘、ご意見がありましたら、コメントいただけると嬉しいです。