2013-02-10 38 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