Created
April 11, 2017 08:13
-
-
Save syou007/5860f204267ea668da13c443a8f3be10 to your computer and use it in GitHub Desktop.
カスタムViewをNibから初期化の最新版 ref: http://qiita.com/syou007/items/a75519195a8d9ff05093
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyCustomView: UIView { | |
... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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