はじめに
基本Androidをやっていますが、 最近iOSのアプリも作り始めました。
storyboard
でレイアウトを組む時にカスタムビューを使うとスッキリするので割と多用するのですが、xib
ファイルの読み込みを綺麗に共通化したくて調べていたら、良いサイトが見つかったのでご紹介します。
xib
の作り方は他の記事でも紹介されているので省略させていただきます。
方法
参考サイトにある通り、UIView
を継承したクラスでxib
を読み込む処理を実装しておき、init
でaddSubview
まで行ってしまうという方法です。
実装
下記の通りに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 Owner
のCustom Class
にCustomView
を設定すればOKです。
もちろんコードからでも使えます。
let customView = CustomView().loadNib() as! CustomView
customView.frame = /* add your frame */
view.addSubview(customView)
カスタムビューを多用するときは、これを使うとスッキリすると思います。
ご参考になれば幸いです。
参考