LoginSignup
18
16

More than 5 years have passed since last update.

xibを利用したカスタムViewを作る時に便利な方法

Last updated at Posted at 2018-04-16

はじめに

基本Androidをやっていますが、 最近iOSのアプリも作り始めました。

storyboardでレイアウトを組む時にカスタムビューを使うとスッキリするので割と多用するのですが、xibファイルの読み込みを綺麗に共通化したくて調べていたら、良いサイトが見つかったのでご紹介します。

xibの作り方は他の記事でも紹介されているので省略させていただきます。

方法

参考サイトにある通り、UIViewを継承したクラスでxibを読み込む処理を実装しておき、initaddSubviewまで行ってしまうという方法です。

実装

下記の通りにNibViewクラスを実装して、通常通りにカスタムビューを作ったら、NibViewを継承するだけです。
ただし、xibファイルのファイル名はクラス名と同じにする必要があります。

コードは参考サイトの内容そのままです。

import UIKit

class NibView: UIView {
    var view: UIView!
    override init(frame: CGRect) {
        super.init(frame: frame)

        // Setup view from .xib file
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Setup view from .xib file
        xibSetup()
    }
}

private extension NibView {

    func xibSetup() {
        backgroundColor = UIColor.clear
        view = loadNib()
        // use bounds not frame or it'll be offset
        view.frame = bounds
        // Adding custom subview on top of our view
        addSubview(view)

        view.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[childView]|",
                                                      options: [],
                                                      metrics: nil,
                                                      views: ["childView": view]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[childView]|",
                                                      options: [],
                                                      metrics: nil,
                                                      views: ["childView": view]))
    }
}

extension UIView {
    /** Loads instance from nib with the same name. */
    func loadNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nibName = type(of: self).description().components(separatedBy: ".").last!
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as! UIView
    }
}
class CustomView: NibView {
}

これでxibを開いて、File's OwnerCustom ClassCustomViewを設定すればOKです。
もちろんコードからでも使えます。

let customView = CustomView().loadNib() as! CustomView
customView.frame = /* add your frame */
view.addSubview(customView)

カスタムビューを多用するときは、これを使うとスッキリすると思います。
ご参考になれば幸いです。

参考

18
16
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
18
16