Contenu connexe
Similaire à よこへな3 15発表資料 最近ViewController をどんな感じで書いているか
Similaire à よこへな3 15発表資料 最近ViewController をどんな感じで書いているか (20)
よこへな3 15発表資料 最近ViewController をどんな感じで書いているか
- 3. 今日の内容
• xib, story boardを使わないでコードだけで iOSを
書くときに,どういう風にViewControllerをかいて
いるか
• 主にビューの描画部分について
- 4. - (void)viewDidLoad{
[super viewDidLoad];
!
UIButton*btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(100, 100, 100, 50);
[btn setTitle:@"Button" forState:UIControlStateNormal];
[btn sizeToFit];
[self.view addSubview:btn];
UILabel*l = [[UILabel alloc]initWithFrame:CGRectMake(100, 150, 100, 50)];
l.text = @"label";
[self.view addSubview:l];
}
昔
viewDidLoad にコントロールの初期化と位置指定
のコードが全て書いてある
- 5. 今
コントロールの初期化と位置指定を分けている
@interface ViewController ()
@property (nonatomic) UIView*titleView;
@property (nonatomic) CustomView*customView;
@end
!
@implementation ViewController
- (void)loadView{
[super loadView];
[self.view addSubview:self.titleView];
[self.view addSubview:self.customView];
}
!
- (void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
CGRect titleViewFrame = CGRectMake(50, 50, 50, 50);
self.titleView.frame = titleViewFrame;
CGRect customViewFrame = CGRectMake(50, 100, 300, 100);
self.customView.frame = customViewFrame;
}
!
#pragma mark - Views
!
- (UIView*)titleView{
if(!_titleView){
_titleView = [UIView new];
_titleView.backgroundColor = [UIColor redColor];
}
return _titleView;
}
!
- (CustomView*)customView{
if(!_customView){
_customView = [CustomView new];
}
return _customView;
}
!
@end
プロパティで宣言
アクセッサで初期化
viewDidLayoutSubviews
で位置指定
loadViewでaddSubview
- 7. - (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self addSubview:self.firstButton];
}
return self;
}
!
#pragma - Views
!
- (void)layoutSubviews{
[super layoutSubviews];
[self.firstButton sizeToFit];
CGRect frame = CGRectMake(0, 0, 60, 30);
self.firstButton.frame = frame;
}
!
- (UIButton*)firstButton{
if(!_firstButton){
_firstButton = [UIButton buttonWithType:UIButtonTypeSystem];
[_firstButton setTitle:@"firstButton" forState:UIControlStateNormal];
}
return _firstButton;
}
今のカスタムビュー
layoutSubviewsで位置指定
initWithFrameで addSubview
あとは VCと同じ