LoginSignup
3
2

More than 3 years have passed since last update.

[入門者によるメモ]swift4 xib作成手順

Last updated at Posted at 2019-10-30

昔少しだけswiftをやっていて、その時なんか苦労した記憶があって敬遠してたけど、めちゃくちゃ簡単でびっくり。
入門者による自分用メモです。

具体的な手順

① TestView.swift ファイルと TestView.xib ファイルを作る
② TextView.xib ファイルの Owner'sFileに TestView.swiftファイルを設定
③Swiftファイルにおいて、xibを読み込む設定をする。
コードは以下の通り


import UIKit

class XibView: UIView {

    // コードから生成した時の初期化処理
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.nibInit()
    }

    // ストーリーボードで配置した時の初期化処理
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.nibInit()
    }

    // xibファイルを読み込んでviewに重ねる
    fileprivate func nibInit() {

        // File's OwnerをTestViewにしたので ownerはself になる
        guard let view = UINib(nibName: "TestView", bundle: nil).instantiate(withOwner: self, options: nil).first as? UIView else {
            return
        }

        view.frame = self.bounds

        view.autoresizingMask = [.flexibleHeight, .flexibleWidth]

        self.addSubview(view)
    }

}

以上でxibファイルをswiftファイルと紐付けができたので、あとはそれを好きな時にレゴブロック的に呼び出すだけ。

Main.storyboardにおいて、xibファイルを設置したいときは、storyboard上でViewファイルなりを設置して、そのカスタムファイルを先に作成したTestView.swift にすれば完成。

StoryboardでViewにおいてどっちが優先されるんだろうと思って、View背景色を緑にしといて、xibファイルの方では青を設定したら青になった。 xibの方が優先されるのかほほーってなりました。swiftの理解がほぼ0なので頑張らなきゃ

参考文献

https://program-life.com/559
すごくわかりやすくて感謝です。ありがとうございますmm

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