简体   繁体   中英

Accessing subview variables from another subview

I have a UIViewController with two sub UIViews. In the first UIView I created a UIView with a green background. After pushing a button in the UIViewController I change this to a red background.

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).

UIViewA.h

@interface UIViewA : UIView

@property UIView *colorView;

UIViewA.m

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

UIViewController.h

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

@interface MainViewController : UIViewController

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

UIViewController.m

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

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

UIViewB.h

#import "UIViewA.h"

@interface UIViewB : UIView

@property UIViewA *ViewA;

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. What you can do is in viewcontroller.m, after you have created viewB, assign 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. In viewB.m

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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