UIViewControllerからViewの要素をUIViewに切り出す手順です。相当久しぶりにObjective-Cを触っていて、
片っ端からハマりまくっていますが少しずつ、新しいことやるのはやはり超楽しいです!
🐮 前提
(1) View的な要素をSampleView.h(m)に切り出し
(2) Viewはスクロールさせる(UIScrollViewの上に要素を載せる)
(3) コントローラ部分はSampleViewController.h(m)に書く。必要な記述のみに絞る
(4) Viewの中でController的な処理を呼び出したい場合は、Delegateで行う
🐯 SampleView.hのサンプル
@protocol sampleViewDelegate -(void) sampleMethod; @end
@interface SampleView : UIView @property(nonatomic, strong) UITextField* textField; @property(nonatomic, weak) id delegate; @end
|
🐰 SampleView.mのサンプル
@interface SampleView @property UITextField* textField; @end
@implementation SampleView
-(id) init { self = [super init]; if(self) { // スクロールビューの生成 UIScrollView scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10, 320, 470)]; [scrollView setContentSize:CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height)]; [self addSubview:scrollView];
// TextFieldの追加 [scrollView addSubview:_textFiled]; } }
-(void) layoutSubviews { [super layoutSubviews];
// TextField CGRect rect = CGRectMake(0, 10, 300, 25); _textField textFiled = [[UITextField alloc]initWithFrame:rectP]; _textField.borderStyle = UITextBorderStyleRoundedRect; _textField.clearButtonMode = UITextFieldViewModeWhileEditing; _textField.returnKeyType = UIReturnKeyDone; [_textField addTarget:self.delegate action:@selector(sampleMethod) forControlEvents: UIControlEventEditingDidEnd]; }
// 背景色の設定 - (void)drawRect:(CGRect)rect { [[UIColor whiteColor] setFill]; UIRectFill(CGRectInset(self.bounds, 0, 0)); }
@end
|
🍣 SampleViewController.mのサンプル
@interface SampleViewController () @property(nonatomic, strong) View *sampleView; @end
@implementation SampleViewController
-(void) loadView { [super viewDidLoad];
_sampleView = [[HogeView alloc] init]; self.view = _sampleView;
// デリゲートのメソッドをこちらで作る _sampleView.delegate = self; }
// イベントハンドラ -(void) sampleMethod { .... }
|
🚜 あとがき
今日は一日、Objective-Cのコードをわかりやすく書くための初歩を勉強しました。
さすがにちょっと書き方を忘れすぎているので、しばらく本を読んでいくつもり!
🐹 参考リンク
逆引きObjective-C for iPhoneアプリ - デリゲートを自作クラスに実装する
iPhone - ViewとViewControllerの繋ぎ方 - Qiita
🖥 VULTRおすすめ
「VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。
最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!