简体   繁体   English

自定义UIView子类添加笔尖子视图

[英]Custom UIView subclass add nib subview

I have a custom UIView subclass let's call it CustomViewA which I init with initWithFrame: and add some UIViews programatically (like a UILabel and so on). 我有一个自定义UIView子类,我们将其CustomViewA ,它是通过initWithFrame:初始化的,并以编程方式添加一些UIViews(例如UILabel等)。 Now there is need for another view to be added to CustomViewA so I created a nib which I lay out some GUI elements inside (one being a UISegmentedControl ) 现在需要将另一个视图添加到CustomViewA因此我创建了一个nib ,并在其中放置了一些GUI元素(一个是UISegmentedControl

Now I'm having some issues on how to correctly add this nib as a subview to CustomViewA . 现在,我遇到一些有关如何正确地将这个笔尖作为子视图添加到CustomViewA Do I need to create .h/.m files for the nib? 我需要为笔尖创建.h / .m文件吗? I want CustomViewA to receive the actions when the segmented control changes values. 我希望CustomViewA在分段控件更改值时接收操作。

Do I need to create .h/.m files for the nib? 我需要为笔尖创建.h / .m文件吗?

No, you needn't. 不,你不需要。

How to receive the actions when the segmented control changes values ? 当分段控件更改值时如何接收动作?

You can set a tag number for segmented control in your xib, it should be unique in all the subviews of the view in your xib. 您可以在xib中为分段控件设置标签号,它在xib视图的所有子视图中应该是唯一的。

You can get the segmented control with the code. 您可以使用代码获取分段控件。 UISegmentedControl *segmentedControl = (UISegmentedControl *)[view viewWithTag:1024]; , once you get the segmented control, you can add an action with the code [segmentedControl addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged]; ,一旦获得分段控件,就可以使用代码[segmentedControl addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];

Edit: How to get the root view of xib? 编辑: 如何获取xib的根视图?

Use the code below: 使用以下代码:

UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"YourXibName" owner:nil options:nil] firstObject];

[[NSBundle mainBundle] loadNibNamed:@"MyNibName" owner:self options:nil];
[self.view addSubview:self.nibView];

In the nib, make sure that the File Owner's class is set to the view controller you are adding it to. 在笔尖中,确保将文件所有者的类设置为要添加它的视图控制器。

You can add properties and IBActions like normal from the nib as well. 您也可以从笔尖添加属性和IBActions就像普通的一样。

I finally figured out what was happening. 我终于知道发生了什么事。 The nib that I added to CustomViewA was added outside CustomViewA s frame. 我添加到CustomViewA的笔尖已添加到CustomViewA的框架之外。 So apparently when a subview is outside the superview's frame it will not intercept touches. 因此,很明显,当子视图在超级视图的框架之外时,它将不会拦截触摸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM