2013-02-10 62 views
1

我在MainViewController中有一个UIButton。
MainViewController有一个childViewContoller。iOS访问parentViewController来更改UIButton的状态setSelected:是

我需要从MainViewController中访问childViewController中的UIButton(tcButton)属性,并将它设置为setSelected:YES在viewDidLoad中。我在我的ChildViewController.m文件中有以下代码,它不起作用。

#import "ChildViewController.h" 
#import "MainViewController.h" 
#import "CoreData.h" 

@interface ChildViewContoller() 
@property (nonatomic, strong) CoreData *coreData; 
@property (nonatomic, strong) MainViewController *mainViewController; 
@end 

@implementation ChildViewController 
@synthesize coreData, mainViewController; 

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.managedObjectContext = [(STAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    [[(mainViewController *)self.parentViewController tcButton] setSelected:YES]; 
} 

回答

2

你的代码有点乱。你为什么在viewDidLoad中创建自己的新实例?这没有意义。如果ChildViewController确实是一个子视图控制器,那么您可以使用self.parentViewController访问父级。你只需要在viewDidLoad中的一行:

-(void)viewDidLoad // Line 4 
{ 

    [[(MainViewController *)self.parentViewController tcButton] setSelected:YES]; // Line 8 
} 
+0

rdelmar:我以为同样的事情,第一次尝试: [self.parentViewController tcButton] setSelected = YES]; ,并给了我错误:无可见@interface'UIViewController'声明选择器'tcButton' 然后我开始使用Google,看到上面的代码。 但是,现在我正在尝试您的代码,并且出现以下错误: 解析问题预期的表达式。 (MainViewController *)的右括号处指向光标箭头。是的,我在最后有一个分号,我复制并粘贴了您的代码。谢谢。 – user1107173 2013-02-10 22:33:55

+0

@ user1107173,哦,对不起,我输入了错误,应该在末尾设置选择:YES(not =)。 – rdelmar 2013-02-10 22:42:19

+0

感谢您的快速回复。我将其更改为setSelected:YES];而且我仍然得到相同的Parse Issue Expected表达式。光标箭头指向(MainViewController *)的右括号。 – user1107173 2013-02-10 22:58:01

1

你的代码有几个问题,但执行你想要的东西的主要想法是获得一个指向mainViewController的指针。有很多方法可以做到这一点,但这里有一个简单的例子来说明如何实现这样的事情。例如在ChildViewContoller的初始化,您可以传递一个指针mainViewController:

@interface ChildViewContoller() 

@property (nonatomic, strong) MainViewController *mainViewController; 

@end 

@implementation ChildViewContoller 

- (id)initWithMainViewController:(MainViewController *)mainViewController 
{ 
    self = [super init]; 

    if (self) 
    { 
     _mainViewController = mainViewController; 
    } 

    return self; 
} 

- (void)viewDidLoad 
{ 
    [_mainViewController.tcButton setSelected:YES]; 
} 

@end 

请不说我还没有测试上面的代码,但你可以明白我的意思。

+0

我得到4个错误的代码: (1)自我= [超级初始化] //不能在init系列的方法之外分配'self' (2)_mainViewController = mainViewController; //意外的接口名'MainViewController'的预期表达式 (3)return self; // void方法initWithMainViewController不应返回值 (4)//在ARC中不允许将Objective-C指针隐式转换为'void'。 – user1107173 2013-02-10 21:30:28

+0

对不起,但正如我所说我无法测试代码,不要按原样使用它。而是尝试了解代码的作用。我修改了一些代码以避免一些错误,请不要说这是一个ARC版本。 – kaal101 2013-02-10 21:56:06