[英]loadNibNamed vs. initWithFrame dilemma for setting frame's height and width
我創建了一個與.xib文件關聯的UIView子類。 此UIView子類將在UIViewController中使用。 在控制器中,我認為有兩個選項可以實例化UIView子類:
MyUIView *myView=[[MyUIView alloc] initWithFrame:aRect];
和
MyUIView *myView = [[[NSBundle mainBundle] loadNibNamed:@"MyUIView"
owner:self
options:nil] lastObject];
我更喜歡允許我執行自定義初始化的第一種方法或其變體。 唯一的問題是我必須指定已在中指定的框架的rect。 xib
(我的意思是框架的高度和寬度MyUIView
)。 是的,我可以在aRect
再次對其進行硬編碼,但是這很繁瑣(例如,當我更改UI在.xib中的位置時,我也必須更新aRect
)。
因此,在自動設置幀rect時應考慮第二種方法。 剩下的問題是我無法自定義初始化程序(例如,我想在初始化期間傳遞額外的參數)。
您的喜好是什么? 您認為哪個更好?
編輯1:受塞爾吉奧的答案啟發,我想到了以下解決方法:
// In MyViewController.m
MyUIView *myView=[[MyUIView alloc] initWithFrame:CGRectMake(x, y, 0.0, 0.0)];
// In MyView.m
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self = [[[NSBundle mainBundle] loadNibNamed:@"UnmovableTagView"
owner:self
options:nil] lastObject];
[self setFrame:CGRectMake(frame.origin.x,
frame.origin.y,
[self frame].size.width,
[self frame].size.height)];
// frame's width and height already determined after
// loadNibNamed was called
...
}
return self;
}
您是否嘗試過使用:
MyUIView *myView=[[MyUIView alloc] initWithFrame:CGRectZero];
我不知道它是否適合您的情況(從筆尖加載視圖),但是當我以編程方式創建自定義視圖時,我成功使用了它。
您可以嘗試一下。
您可以為視圖定義自己的init
方法:
-(id)initWithPosition:(CGPoint)pos;
然后致電:
-(id)initWithPosition:(CGPoint)pos {
if (self = [super initWithFrame:{pos,{0,0}}]) {
self = [[[NSBundle mainBundle] loadNibNamed:@"UnmovableTagView"
owner:self
options:nil] lastObject];
[self setFrame:CGRectMake(frame.origin.x,
frame.origin.y,
[self frame].size.width,
[self frame].size.height)];
// frame's width and height already determined
// after loadNibNamed was called
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.