简体   繁体   English

如何将子视图添加到另一个子视图并使其显示?

[英]How can I add a subview to another subview and make it appear?

What I am doing it creating a UIImageView and hope to add it to a UIScrollingView as its scrolling content, but it never appears. 我正在执行的操作是创建UIImageView并希望将其作为滚动内容添加到UIScrollingView中,但是它从未出现过。 So I tried the following code and the problem is now pretty clear to me. 所以我尝试了以下代码,现在问题对我来说很清楚。 How can I add a subview to another subview? 如何将子视图添加到另一个子视图?

 //in myViewController.m
 @synthesize scrollView = _scrollView;
 - (void) viewDidLoad{ 
     UIView* simpleView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,200)];
     [simpleView setBackgroundColor: [UIColor BlueColor]];
     [self.view addSubview: simpleView]  //this would work, the simple view appears
     [self.scrollView addSubview: simpleView]  //this would not work, the simple view doesn't appear
 }

the scrollView property is hooked up with ScollView in the storyboard, which is the only thing in that controller scrollView属性与情节提要中的ScollView关联,这是该控制器中唯一的东西

You need to do this: 您需要这样做:

[self.view addSubview: scrollview]  
[self.scrollView addSubview: simpleView] 

Basically add one on top of the other not everything is being stacked on the view. 基本上在另一个之上添加一个,而不是将所有内容堆叠在视图上。 Image on top of view on top of self pretty much 在自己之上的视图之上的图像

One possibility: The scroll view might not be linked to the scrollView property from your xib/storyboard. 一种可能:滚动视图可能未从xib / storyboard链接到scrollView属性。 Set a breakpoint in this method and check it. 在此方法中设置一个断点并进行检查。

A view can only have one superView. 一个视图只能有一个 SuperView。

So when you do this: 因此,当您执行此操作时:

[self.view addSubview: simpleView];
[self.scrollView addSubview: simpleView];

You just set the simpleView superView to self.view then you replace it by self.scrollView. 您只需将simpleView超级视图设置为self.view,然后将其替换为self.scrollView。 simpleView is no longer the subview of self.view. simpleView不再是self.view的子视图。

As said by ECEsurfer, stack your views: 正如ECEsurfer所说,将您的观点堆叠起来:

[self.view addSubview: scrollview];
[self.scrollView addSubview: simpleView];

Hope it helps ! 希望能帮助到你 !

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

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