MacアプリでCustomViewを追加する
Macアプリ で CustomView を追加します。
iOS だと こういう感じ で実装しますが、Macアプリはすこし手順が多いようです。
参考記事
How to use custom NSView in Interface Builder?
NSView とxib ファイルを追加
https://gyazo.com/fe4fa1f3da4e2245982b2bedfea8cd38
まずは、NSViewのサブクラス(今回はCustomViewという名前にしました)と、おなじ名前のxibファイルを追加します。
・File's Owner を設定
https://gyazo.com/1c960aba2c6d2b0db5efa26410fe96dc
xib ファイルの File's Owner を選択して、Identity Inspector の Class 欄で CustomViewを選択します。
画面レイアウト作成
https://gyazo.com/ecc0c76312ff83f22c09b41815bedf3c
CustomView に部品を追加して、画面レイアウトを作成します。
今回は、 CustomView が表示されているかわかりやすいように、「カスタムクラス」と書いたラベルをおきました。
Viewのアウトレットを接続
https://gyazo.com/63cb666c1890b17374129758d0b7604d
CustomView のトップレベルの View を IBOutlet で接続します。
init 処理を追加
https://gyazo.com/65cd9b29cae53a17edcf8e83311af57f
CustomView に init 処理を追加します。
参考記事には init(frame: ) は書かれていませんでしたが、念のため追加しました。
code: Swift
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
loadNib()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
loadNib()
}
func loadNib() {
let name = String(describing: CustomView.self)
if let nib = NSNib(nibNamed: name, bundle: Bundle(for: type(of: self))) {
nib.instantiate(withOwner: self, topLevelObjects: nil)
var newConstraints = NSLayoutConstraint()
for oldConstraint in view.constraints {
let firstItem = oldConstraint.firstItem === view ? self : oldConstraint.firstItem as Any
let secondItem = oldConstraint.secondItem === view ? self : oldConstraint.secondItem as Any
newConstraints.append(NSLayoutConstraint(item: firstItem,
attribute: oldConstraint.firstAttribute,
relatedBy: oldConstraint.relation,
toItem: secondItem,
attribute: oldConstraint.secondAttribute,
multiplier: oldConstraint.multiplier,
constant: oldConstraint.constant))
}
for newView in view.subviews {
addSubview(newView)
}
addConstraints(newConstraints)
}
}
ViewControllerにNSViewを追加
https://gyazo.com/647508c513be6ac01996b3bdf21f2d7d
カスタムビューを表示したい ViewController に NSView を追加します(カスタムビューを追加するときは、 Object Library で Custom View を選択します)。
カスタムビューのクラスを設定
https://gyazo.com/7f5bc20381b8cf8b66835301f7c2ec37
先ほど追加したカスタムビューを選択して、Identity Inspector の Class 欄で CustomViewを選択します。
実行
https://gyazo.com/7765d9772701898dbb6f4ec854435be0
シミュレーターを実行すると、無事にカスタムクラスが表示されました。