簡體   English   中英

如何在不使用segue的情況下在視圖控制器之間傳遞數據

[英]How to pass data between the view controllers without using segue

我正在使用故事板開發iPad應用程序。 在我的應用程序中,我使用segue模態顯示從第一個視圖控制器連接了一個模態視圖控制器。模態視圖通過單擊模式視圖中出現的一個按鈕來解除。如何將模態視圖控制器中的一個字典傳遞給第一個視圖控制器而不使用Segue公司。

您可以使用通知傳遞值。

// Send Data    
   NSDictionary *aDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                              anObject, @"objectName", 
                              anotherObject, @"objectId",
                              nil] autorelease];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"AnythingAtAll" object:nil userInfo:aDictionary];

您可以從您觀察到的入站通知中檢索字典。 在發布通知之前添加觀察者。

//this might be in your init method or a viewDidLoad method of your FirstViewController

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyAction:) name:@"AnythingAtAll" object:nil];
enter code here

//獲取數據

-(void)anyAction:(NSNotification *)anote
{
NSDictionary *dict = [anote userInfo];
AnyClass *objectIWantToTransfer = [dict objectForKey:@"objectName"];
}

請注意,您應該在dealloc方法中刪除對象作為觀察者。

[[NSNotificationCenter defaultCenter] removeObserver:self]

使用委托可能。 通過這個

在視圖控制器之間傳遞數據

它有簡單而完美的答案。

你可以通過ctrl +從第一個控制器拖動到第二個控制器來創建一個不受按鈕限制的Segue(不要忘記給這個segue和標識符)。

Next在按鈕的IBAction中(通過Interface Builder設置或通過addTarget:self action:forControlEvents:),您可以調用[self performSegueWithIdentifier:@“YourSegueIdentifier”sender:button];

您可以像往常一樣將數據傳遞給第二個控制器 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

- (void)transitionFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion {

SecondViewController *secVC = (SecondViewController*)toViewController;
secVC.property = self.property

}

使用協議是向先前控制器或任何其他控制器發送信息的最佳過程

在你的viewcontrooler中,你在.h中寫了這個

@class yourclassName;

typedef void(^ yourclassName Callback)(NSDictionary *);

@protocol yourclassName Delegate @required - (void)yourclassNamedidReceiveData:(NSDictionary *)dataDict;

@結束

in .m file

@synthesize delegate=_delegate;
@synthesize callbackBlock=_callbackBlock;

在某些按鈕操作中,您需要將信息傳回去,請寫下此信息

[self yourclassNamedidReceiveData:yourDictHere]; // you can use any as per your requirement

注意:yourclassNamedidReceiveData方法在一個類中聲明,現在它在另一個類中實現,您將在該類中調用此類

在您之前的Controller中(您嘗試在類A中提供類(假設classA和classB),第一個類是classA,並且在ClassA中呈現的類是classB。)

- (void) yourclassNamedidReceiveData:(NSDictionary *)dataDict
{

}

注意*不要忘記將委托設置為classB EX:classBObject.delegate = self;
希望這會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM