0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift] [Xcode] Outlet Collectionを使ってみた

Last updated at Posted at 2022-01-24

Outlet Collection とは

画面上に似たような部品があった時に変数をまとめることができるもの

例えば以下のようなLabelを

class ViewController: UIViewController {
    @IBOutlet weak var numberLabel1: UILabel!
    @IBOutlet weak var numberLabel2: UILabel!
    @IBOutlet weak var numberLabel3: UILabel!
    @IBOutlet weak var numberLabel4: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
}

こんな感じに書ける

class ViewController: UIViewController {
    @IBOutlet var numberLabel: [UILabel]!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
}

完成品

完成イメージ.png

実装

Ctrlキーを押しながら一つ目のLabelをソースコードまで持ってきてConnectionをOutLet Collectionに設定してConnectを押す
スクリーンショット 2022-01-24 16.03.02.png

StoryBoardの左側にある黄色ボタン?を押すと右側にOutlet Collectionsという画面が出てくる。
スクリーンショット 2022-01-24 16.05.32.png

右側のボタンをStoryboard上の画面のLabelにドラッグするとLabelが追加される
スクリーンショット 2022-01-24 16.06.08.png

ソースコード内に下記を追記して終了

class ViewController: UIViewController {
    
    @IBOutlet var numberLabel: [UILabel]!
    override func viewDidLoad() {
        super.viewDidLoad()
        for i in 0..<4 {
            numberLabel[i].text = "\(i)"
        }
    }
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?