Storyboard上に配置しているUI部品のプロパティを、Storyboard上から設定できるということを最近知りました。これってみんな知ってるんですかね?

独自のボタンクラス

サンプルとして角丸半径や輪郭線の幅を外部から設定できるUIButtonのサブクラスを用意しました。公開プロパティcornerRadiusborderWidthの値をStoryboardから設定する感じで使います。

1// CustomeButton.h
2#import <UIKit/UIKit.h>
3
4@interface CustomButton : UIButton
5
6@property (nonatomic, assign) int cornerRadius;
7@property (nonatomic, assign) int borderWidth;
8
9@end

awakeFromNibメソッドを定義することでNibの読み込み時の処理を書けるようです。

 1// CustomeButton.m
 2#import "CustomButton.h"
 3
 4@implementation CustomButton
 5
 6- (void)awakeFromNib
 7{
 8    self.layer.cornerRadius = self.cornerRadius;
 9    self.layer.borderWidth  = self.borderWidth ;
10}
11
12@end

Storyboardでの設定

StoryboardでUIButtonを置いたらこの画像のようにクラスや値をセットします。

なお余談ですが、Key Pathには先ほど定義したCustomButtonのプロパティだけでなく、UIButtonのプロパティも使うことができます。

結果

左Storyboard、右シミュレータです。この程度のサンプルではあまりメリットがないかもしれませんが、オリジナルのUIコンポーネントを作ってちょいちょいやりたいときには便利かも。

ネタ元

[ObjC] – UIButton with rounded corners