[英]loadNibNamed vs. initWithFrame dilemma for setting frame's height and width
I created a UIView subclass associated with .xib file. 我创建了一个与.xib文件关联的UIView子类。 This UIView subclass is to be used in a UIViewController.
此UIView子类将在UIViewController中使用。 In the controller, I think there are two options how we instantiate the UIView subclass:
在控制器中,我认为有两个选项可以实例化UIView子类:
MyUIView *myView=[[MyUIView alloc] initWithFrame:aRect];
and 和
MyUIView *myView = [[[NSBundle mainBundle] loadNibNamed:@"MyUIView"
owner:self
options:nil] lastObject];
I prefer the first approach or its variants that allow me to perform custom initialization. 我更喜欢允许我执行自定义初始化的第一种方法或其变体。 The only problem is that I have to specify a frame's rect, which was already specified in .
唯一的问题是我必须指定已在中指定的框架的rect。
xib
(I mean frame's height and width of MyUIView
). xib
(我的意思是框架的高度和宽度MyUIView
)。 Yes, I can hardcode it again in aRect
, but this is tedious to maintain (eg, when I change position of UIs in .xib, I have to update aRect
, too). 是的,我可以在
aRect
再次对其进行硬编码,但是这很繁琐(例如,当我更改UI在.xib中的位置时,我也必须更新aRect
)。
So the second approach should come into mind as the frame rect is automatically set. 因此,在自动设置帧rect时应考虑第二种方法。 The remaining problem is I cannot customize the initializer (say, I want to pass extra parameters during initialization).
剩下的问题是我无法自定义初始化程序(例如,我想在初始化期间传递额外的参数)。
What's your preference? 您的喜好是什么? Which one is better in your opinion?
您认为哪个更好?
EDIT1: Inspired by sergio's answer, I came out with this workaround: 编辑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;
}
Have you tried using: 您是否尝试过使用:
MyUIView *myView=[[MyUIView alloc] initWithFrame:CGRectZero];
I don't know if it works in your case (loading the view from a nib), but I use it successfully when I create my custom view programmatically. 我不知道它是否适合您的情况(从笔尖加载视图),但是当我以编程方式创建自定义视图时,我成功使用了它。
You can give it a try. 您可以尝试一下。
you could define your own init
method for your view: 您可以为视图定义自己的
init
方法:
-(id)initWithPosition:(CGPoint)pos;
and then call: 然后致电:
-(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.