简体   繁体   English

从另一个子视图访问子视图变量

[英]Accessing subview variables from another subview

I have a UIViewController with two sub UIViews. 我有一个带有两个子UIViews的UIViewController。 In the first UIView I created a UIView with a green background. 在第一个UIView中,我创建了一个绿色背景的UIView。 After pushing a button in the UIViewController I change this to a red background. 按下UIViewController中的按钮后,将其更改为红色背景。

And now I want to change it to a purple background, but since i changed the background in the UIViewController I'm not able to change it (again). 现在我想将其更改为紫色背景,但是由于我在UIViewController中更改了背景,所以我无法再次更改它。

UIViewA.h UIViewA.h

@interface UIViewA : UIView

@property UIView *colorView;

UIViewA.m UIViewA.m

...
colorView = [[UIView alloc]init];
[colorView setBackgroundColor:[UIColor greenColor]];
...

UIViewController.h UIViewController.h

#import "UIViewA.h"
#import "UIViewB.h"

@interface MainViewController : UIViewController

@property UIViewA *viewA;
@property UIViewB *viewB;

UIViewController.m UIViewController.m

...
viewA = [[UIViewA alloc]init];
viewB = [[UIViewB alloc]init];
...

-(void)changeColor
{
    [[viewA colorView] setBackgroundColor:[UIColor redColor]];
}

UIViewB.h UIViewB.h

#import "UIViewA.h"

@interface UIViewB : UIView

@property UIViewA *ViewA;

UIViewB.m UIViewB.m

...
ViewA = [[UIViewA alloc]init];
[[ViewA colorView] setBackgroundColor:[UIColor greenColor]];
// ^^ That rule doesn't seem to work. No errors were given.
...

EDIT: A shorter example of what I'm trying to do. 编辑:我正在尝试做的简短示例。 在此处输入图片说明

If I understand you right, you want to change viewA's background color in viewB. 如果我理解正确,您想在viewB中更改viewA的背景颜色。 What you can do is in viewcontroller.m, after you have created viewB, assign viewB.viewA = self.viewA . 您可以执行的操作是在viewcontroller.m中,在创建viewB之后,分配viewB.viewA = self.viewA and in viewB.m, do not create a new viewA, instead use the property self.viewA, thus you can change the viewA's background color. 在viewB.m中,不要创建新的viewA,而应使用属性self.viewA,这样就可以更改viewA的背景颜色。 In viewB.m viewB.m

[[self.viewA colorView] setBackgroundColor:[UIColor greenColor]];

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

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