
UILabelが3つはいったUIViewのサブクラスを作ってみる。
クラス名は"MyView"
label1, label2, label3として、それぞれにクラスの外から文字を設定できるようにする。
クラス構造定義
@interface MyView : UIView{
UILabel* label1;
UILabel* label2;
UILabel* label3;
}
@property(nonatomic, readonly)UILabel* label1;
@property(nonatomic, readonly)UILabel* label2;
@property(nonatomic, readonly)UILabel* label3;
@end
UILabel* label1;
UILabel* label2;
UILabel* label3;
この3行で、クラス内に変数を宣言する。
これを書くことで、クラス内から変数を操作できる。
@property(nonatomic, readonly)UILabel* label1;
@property(nonatomic, readonly)UILabel* label2;
@property(nonatomic, readonly)UILabel* label3;
@property宣言をすると、変数をクラスの外部から操作できるようになる。
変数そのものを変更する必要はないので、読み込みオンリーで◎
次の実装の@synthesizeとセット。
クラス実装
@implementation MyView
@synthesize label1;
@synthesize label2;
@synthesize label3;
- (id)init{
self = [super init];
self.frame = CGRectMake(0, 0, 320, 480);
label1 = [[UILabel alloc] init];
label1.frame = CGRectMake(10, 50, 300, 20);
[self addSubview:label1];
label2 = [[UILabel alloc] init];
label2.frame = CGRectMake(10, 100, 300, 20);
[self addSubview:label2];
label3 = [[UILabel alloc] init];
label3.frame = CGRectMake(10, 150, 300, 20);
[self addSubview:label3];
return self;
}
@end
@synthesize label1;
@synthesize label2;
@synthesize label3;
この3行でさっき宣言した@propertyの設定を実装する。
気にしなくていいけど、ウラでこっそり自動でアクセスメソッドが作られてる。
- (id)init{
self = [super init];
~
return self;
}
クラスの初期化メソッド"init"に初期化ロジックを書く。
selfがクラス自身。
[super init]で親クラスのinitを実行!
その結果を自分として、あとはUILabelを3つ追加するロジックを書いてる。
これで定義は完了!
使うとこはこんな感じ。
UIView* oya = [[UIView alloc]init];
oya.frame = CGRectMake(0, 0, 320, 480);
MyView* view = [[MyView alloc]init];
view.label1.text = @"LABEL1";
view.label2.text = @"LABEL2";
view.label3.text = @"LABEL3";
[oya addSubview:view];
結果はこうなります。

以上であります!
またこんど~
