Skip to content

Instantly share code, notes, and snippets.

@syou007
Created April 11, 2017 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syou007/5860f204267ea668da13c443a8f3be10 to your computer and use it in GitHub Desktop.
Save syou007/5860f204267ea668da13c443a8f3be10 to your computer and use it in GitHub Desktop.
カスタムViewをNibから初期化の最新版 ref: http://qiita.com/syou007/items/a75519195a8d9ff05093
class UINibView: UIView {
// コードから初期化はここから
override init(frame: CGRect) {
super.init(frame: frame)
comminInit()
}
// Storyboard/xib から初期化はここから
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
comminInit()
}
// 初期化後に呼びされる。
func afterInit() {}
// xibからカスタムViewを読み込んで準備する
private func comminInit() {
// MyCustomView.xib からカスタムViewをロードする
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: self.className, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
addSubview(view)
// カスタムViewのサイズを自分自身と同じサイズにする
view.translatesAutoresizingMaskIntoConstraints = false
let bindings = ["view": view]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|",
options:NSLayoutFormatOptions(rawValue: 0),
metrics:nil,
views: bindings))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|",
options:NSLayoutFormatOptions(rawValue: 0),
metrics:nil,
views: bindings))
self.afterInit()
}
// このメソッドはextensionにすると使い勝手が良いです。
var className: String {
get {
return type(of: self).className
}
}
}
class MyCustomView: UIView {
...
}
class MyCustomView: UINibView {
// ここのコードは不要です。
// 以下のコードはサンプルですが、後は普通に接続できます。
@IBOutlet weak private var nameLabel:UILabel!
// 初期化後
override func afterInit() {
nameLabel.text = "テスト"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment