XcodeのstoryboardからUI部品にプロパティを与える方法
移転しました →
Storyboard上に配置しているUI部品のプロパティを、Storyboard上から設定することができるということを最近知りました。これってみんな知ってるんですかね?
独自のボタンクラス
サンプルとして角丸半径や輪郭線の幅を外部から設定できるUIButton
のサブクラスを用意しました。公開プロパティcornerRadius
、borderWidth
の値をStoryboardから設定する感じで使います。
// CustomeButton.h #import <UIKit/UIKit.h> @interface CustomButton : UIButton @property (nonatomic, assign) int cornerRadius; @property (nonatomic, assign) int borderWidth; @end
awakeFromNib
メソッドを定義することでNibの読み込み時の処理を書けるようです。
// CustomeButton.m #import "CustomButton.h" @implementation CustomButton - (void)awakeFromNib { self.layer.cornerRadius = self.cornerRadius; self.layer.borderWidth = self.borderWidth ; } @end
Storyboardでの設定
StoryboardでUIButtonを置いたらこの画像のようにクラスや値をセットします。
なお余談ですが、Key Path
には先ほど定義したCustomButton
のプロパティだけでなく、UIButton
のプロパティも使うことができます。
結果
左Storyboard、右シミュレータです。この程度のサンプルではあまりメリットがないかもしれませんが、オリジナルのUIコンポーネントを作ってちょいちょいやりたいときには便利かも。