LoginSignup
2
2

More than 3 years have passed since last update.

Global変数でレイアウトを管理する時の注意点

Posted at

なぜGlobal変数

scrollViewに配置するそれぞれのViewをカスタムクラスとして保持していたため、それぞれのクラス間での変数の値を統一したいから。その際の注意点として、scrollViewにLabelなどを配置し、非同期処理によって文字列をaddする場合などにLabelの高さをそれぞれのクラスで更新することが必要。

どう使う

これを

Global.swift
var labelHeight: CGFloat = 0

class ViewController: UIViewController {
    var label: UILabel!
    var profileLabelHeight: CGFloat = labelHeight

    override func viewDidLoad() {
        super.viewDidLoad() 
        setup()           
    }
    func setup() {
        //global変数が更新された時に値が変わらない
        label = UILabel()
        label.frame.size.height = profileLabelHeight  
    }
}

こう

Global.swift
var labelHeight: CGFloat = 0

class ViewController: UIViewController {
    var label: UILabel!
    var profileLabelHeight: CGFloat { 
        //呼ばれるとprofileLabelHeightを更新する
        return labelHeight
    }
    override func viewDidLoad() {
        super.viewDidLoad() 
        setup()           
    }
    func setup() {
        label = UILabel()
        label.frame.size.height = profileLabelHeight  
    }
}

終わり

2
2
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
2
2