2016-07-16 6 views
0

スイッチのリンクに問題があります。私はアウトレットとしてスイッチを接続する方法を理解し、アクションの値のブール値の状態を変更するが、私は別のビューコントローラでアクションを実行するスイッチが必要です。Xcodeでスイッチをリンクする際の問題点

私はビューコントローラAと呼ばれるメインテーブルビューコントローラを持っています。私は2番目のビューコントローラを持っています。コントローラBをビューコントローラと呼び、メニューバーをコントロールします(通常のビューコントローラではなく、ビュー)を表示します。メニューを開き、サイドバーのスイッチを押して、ビューコントローラAによって制御されるメインテーブルビューに何か変更を加えたいと思っています。

私はこれを達成する方法はありますか?私はBからビューコントローラAのIBOutletsにアクセスしたり変更したりする方法がないようです。スイッチにリンクされたBでアクションを持つことができ、値のブール状態を変更し、コントローラ内でアクションを待っている方法がありますかブール値の変化に対応するA?この問題を解決する方法がわかりません。ヘルプは高く評価されています!

答えて

1

delegation patternを使用してください。あなたは、コントローラAで待機しているアクションがあるでしょうが、その代わりにBに変更された値に応答してのアクションはBによってトリガされたときに適切な

ViewControllerB.h

// Create delegate protocol and property 
@protocol ViewControllerBDelegate <NSObject> 
    - (void)switchPressed:(BOOL)switchStatus; 
@end 

@interface ViewControllerB : NSObject 
    @property (nonatomic,weak) id<ViewControllerBDelegate> delegate; 
@end 

ViewControllerB.m

// When switch is tapped, call delegate method if it is implemented by delegate object 
- (IBAction)flip: (id) sender { 
    UISwitch *onoff = (UISwitch *) sender; 
    if ([self.delegate respondsToSelector:@selector(switchPressed:)]) { 
     [self.delegate switchPressed:onoff.on]; 
    } 
} 

ViewControllerA.h

// Conform to ViewControllerB protocol 
#import ViewControllerB.h 

@interface ViewControllerA : NSObject,ViewControllerBDelegate 

ViewControllerA.m

// Set self (VC A) as VC B's delegate 
- (void)ViewDidLoadOrSomeOtherFunction {  
    ViewControllerB *vcB = [[ViewControllerB alloc] init]; 
    vcB setDelegate = self; 
} 

// Implement delegate method 
- (void)switchPressed:(BOOL)switchStatus { 
    if (switchStatus) { 
     // Make changes on VC A 
    } 
} 
関連する問題