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

时间:2014-10-04 13:39:17

标签: ios objective-c xcode subview

我有一个带有两个子UIViews的UIViewController。 在第一个UIView中,我创建了一个绿色背景的UIView。 按下UIViewController中的按钮后,我将其更改为红色背景。

现在我想把它改成紫色背景,但是因为我改变了UIViewController中的背景,我无法再改变它(再次)。

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

修改 我尝试做的一个较短的例子。 enter image description here

1 个答案:

答案 0 :(得分:0)

如果我理解你,你想在viewB中改变viewA的背景颜色。您可以在viewcontroller.m中执行的操作,在创建viewB之后,分配viewB.viewA = self.viewA。并且在viewB.m中,不要创建新的viewA,而是使用属性self.viewA,这样就可以更改viewA的背景颜色。在viewB.m

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