使用带有用户交互的nib加载UIView

时间:2021-10-03 12:59:22

There are plenty of questions regarding loading UIViews from Nib files, so that isn't the issue. I have my UIView loading from a Nib file just fine, the trouble is, depending on how I set the view, I either don't have user interaction, or IBActions cause a crash.

关于从Nib文件加载UIViews有很多问题,所以这不是问题。我从Uib文件加载UIView就好了,麻烦的是,根据我设置视图的方式,我要么没有用户交互,要么IBActions导致崩溃。

Scenario 0:

场景0:

- (id) init {
self = [super init];

if (self) {
    [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
    [self addSubview:self.view];
}

return self;

}

}

Outcome: This loads the view from the Nib, but UIButtons are not tappable. I've also noticed the main view of the View Controller behind this is still interactive, even though this view is supposed to block it.

结果:这会从Nib加载视图,但UIButtons不可点击。我还注意到,后面的View Controller的主视图仍然是交互式的,即使这个视图应该阻止它。

Scenario 1: Changing this line

场景1:更改此行

[self addSubview:self.view]

to

self = (MyView*)self.view;

Causes the view to block the main view controller view behind it, and a button subview becomes tappable, but... when I connect the button's selector to an IBAction it causes a crash with the error:

导致视图阻止其后面的主视图控制器视图,并且按钮子视图变为可点击,但是...当我将按钮的选择器连接到IBAction时,它会导致崩溃并出现错误:

-[MyView performSelector:withObject:withObject:]: message sent to deallocated instance 0x12f1cff0

Why is my view being deallocated in this scenario? Before someone asks, I am adding the subview simply like so:

为什么我的视图在这种情况下被解除分配?在有人要求之前,我正在添加子视图,就像这样:

MyView *myView = [[MyView alloc] init];
[self.view addSubview:myView];

Edit: Interestingly, I also notice that awakeFromNib is never being called (in either scenario). Should it be?

编辑:有趣的是,我还注意到awakeFromNib永远不会被调用(在任何一个场景中)。应该是吗?

1 个解决方案

#1


1  

the designated initializer is initWithFrame

指定的初始化程序是initWithFrame

apart from that :: how is the IBOutlet for view?

除此之外:: IBOutlet如何查看?

#1


1  

the designated initializer is initWithFrame

指定的初始化程序是initWithFrame

apart from that :: how is the IBOutlet for view?

除此之外:: IBOutlet如何查看?