![](/img/trans.png)
[英]Passing a string from one viewcontroller to another Tabbarcontroller
[英]Passing data from one ViewController to another when switching tabBarController index instead of segueing
我的應用程序包含一個帶有兩個選項卡的tabBarController
。 選項卡編號0
包含SearchViewController
,選項卡編號1
包含MatchCenterViewController
。 我想要做的是設置的值是什么MatchCenterViewController
小號didAddNewItem
切換到該選項卡前財產。 我知道,如果我使用segue進行此操作,則將這樣做:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"ShowMatchCenterSegue"]) {
MatchCenterViewController *controller = (MatchCenterViewController *) segue.destinationViewController;
self.didAddNewItem = 1;
controller.didAddNewItem = self.didAddNewItem;
}
}
但是我不想用SEGUE要做到這一點,我希望它簡單地設置didAddNewItem
的MatchCenterViewController
之前調用[self.tabBarController setSelectedIndex:1];
。 是否有可能做到這一點?
您應該能夠從[self.tabBarController viewControllers]
拉出視圖控制器
一些偽代碼供您嘗試:
UIViewController *toViewController = [self.tabBarController viewControllers][1];
if ([toViewController isKindOfClass:[MatchCenterViewController class]]) { // This is just for the sake of safety. Good practice to get into type checking before you cast.
MatchCenterViewController *matchViewController = (MatchCenterViewController *)toViewController;
matchViewController.didAddNewItem = true; // Really this should be a Bool!
}
[self.tabBarController setSelectedIndex:1];
最好使用協議和委托,這是將數據傳遞到另一個視圖控制器的最干凈的方法。 它還使您的代碼脫鈎,以便以后管理。 例如,您構建沒有UITabbarController的iPad版本。
Define a protocol in SearchViewController.h:
//under the #import
@protocol SearchViewControllerDelegate
//define a property to send delegate messages to
@property (nonatomic,strong) id <SearchViewControllerDelegate> delegate;
//after @end
@protocol SearchViewControllerDelegate <NSObject>
- (void)searchViewControllerDidSearchWithResult:(NSArray *)result;
Then when you are setting up the view controllers assign MatchViewController to be the SearchViewControllers delegate.
//in SearchViewController.m send the delegate message
[self.delegate searchViewControllerDidSearchWithResult:arr];
Then in MatchViewController adopt the protocol to get messages.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.