LoginSignup
0
0

More than 5 years have passed since last update.

Xcode 他クラスのメソッドを使う その2 シングルトン

Last updated at Posted at 2018-05-04

前回、AppDelegateを使った方法をあげましたらアドバイスを頂き、実際に、シングルトンを使ってやってみました。

備忘録を含めた意味でも再投稿。

前回の記事
https://qiita.com/gurensouen/items/0f11c80c10afbc36653a

開発環境
Xcode 9.0
Swift 4.0

Storyboardはこんな感じ
スクリーンショット 2018-05-04 22.25.04.png

ボタンを押したら、「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()
    }

今回はこんな感じで仕上げました。
誰かの参考になったら幸いです。

ご指摘、ご意見がありましたら、コメントいただけると嬉しいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0