IOS Custom View 三部曲 Part 1 (Custom View With xib)

Repo來源:CustomView
相關檔案:

Step 1

  • 建立一個CustomView類別,並且繼承自UIView
    ex: CustomView.h & CustomView.m

  • 然後,接著建立同名的xib檔案
    ex: CustomView.xib

Step 2

  • 選到xib檔
  • 點選File's Owner
  • command + option + 3
  • 輸入上你的Custom Class名稱
    ex: CustomView

下圖是TemplateView1.xib,因此點選File's Owner後,填入TemplateView1

TemplateView1.xib

Step 3

  • 實作 initWithCoder 方法
CustomView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void) setup{
NSString *nibName = NSStringFromClass([self class]);
UINib *nib = [UINib nibWithNibName:nibName bundle:nil];
[nib instantiateWithOwner:self options:nil];
//Add the view loaded from the nib into self.
[self addSubview:self.view];
}

- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];

if (self) {
[self setup];
}
return self;
}

Step 4 (選擇性實作)

  • 如果你想要在Storyboard輸入你的相關參數
  • 在你的Storyboard拉入一個UIView
  • 點選剛剛的UIView -> command + option + 3 -> 輸入你的Custom Class name
  • 找到User denfined Runtime Attributes,並且填入你想輸入的參數

Storyboard

Key Path Type Value
vTitle String the title
  • CustomView.h建立個property
CustomView.h
1
@property (assign) NSString* vTitle;
  • Implement awakeFromNib in CustomView.m
CustomView.m
1
2
3
- (void)awakeFromNib {
labelTitle.text = vTitle;
}