2013-03-27 14 views
0

的ViewController通過DismissViewController傳遞一個動作到View

  • 的UIWebView:webView - 一個簡單的UIWebView
  • 的UIButton:aboutButton - 帶你到AboutViewController

AboutViewController

  • 的UIButton:websiteButton - 連接到clickWebsiteButton
  • IBAction爲:clickWebsiteButton - 解僱AboutViewController,負載http://websiteURL.com/webView(這是視圖控制器內)

AboutViewController代碼

// AboutViewController.h 

#import "ViewController.h" 

@class ViewController; 

@interface AboutViewController : UITableViewController <UIWebViewDelegate> { 
    ViewController *viewController; 
} 


// AboutViewController.m 

-(IBAction)clickWebsiteButton:(id)sender { 
    [viewController.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://websiteURL.com/"]]]; 
    [self dismissModalViewControllerAnimated:YES]; 
} 

問題

我希望能夠通過IBAction解除視圖時在UIWebView中加載http://websiteURL.com/。到目前爲止,它所做的只是解除視圖,但不會在WebView中加載URL。 WebView正在工作並正確加載URL,我只是在從另一個視圖加載該URL時遇到麻煩。有任何想法嗎?

感謝

+0

確定那'viewController'收到消息?你如何設置AboutViewController的'viewController'屬性? – ckhan 2013-03-27 00:37:04

+0

我不認爲ViewController收到消息。我認爲這將是唯一合乎邏輯的解釋。 – 2013-03-27 00:42:53

+0

這當然可以解釋它。那麼,你如何設置實例變量? – ckhan 2013-03-27 04:21:36

回答

0

一種選擇是使用委託回調。用你當前的代碼,viewController即時是零。我有一個示例如何實現代理模式here

1

我回答了關於持久性數據存儲的your other question。這是讓viewControllers共享數據的一種不同方式,所以你可能不再需要這個了,但以防萬一...

問題是,你在提交viewController之前調用了一個方法, viewController(aboutViewController)。它需要在解散過程完成後調用。

這種方法:

dismissModalViewControllerAnimated: 

不贊成在iOS6的,由於iOS5的鼓勵您使用這個代替

dismissViewControllerAnimated:completion: 

其中completion需要一個塊參數。完成塊中的代碼將在解散完成後執行。你可以在這裏發送一條消息給呈現的viewController。

self.presentingViewController是其中提出aboutViewController所述的viewController基準 - 它是由iOS裝置提供作爲呈現過程的一部分。但是你不能在完成塊中使用它,因爲它在解散過程中被取消,所以你需要首先將它複製到局部變量。

在aboutViewController ...

-(IBAction)clickWebsiteButton:(id)sender 
{ 
     //to use self.presentingViewController in the completion block 
     //you must first copy it to a local variable 
     //as it is cleared by the dismissing process 

    UIViewController* presentingVC = self.presentingViewController; 

    [self.presentingViewController dismissViewControllerAnimated:YES 
            completion: 
    ^{ 
     if ([presentingVC respondsToSelector:@selector(loadRequestWithString:)]) { 
      [presentingVC performSelector:@selector(loadRequestWithString:) 
           withObject:@"http://websiteURL.com/"]; 
     } 
    }]; 
} 

在你提出的viewController,做一個方法接受字符串參數:

- (void) loadRequestWithString:(NSString*)webString 
{ 
    NSURL* requestURL = [NSURL URLWithString:webString]; 
    [self.webView loadRequest:[NSURLRequest requestWithURL:requestURL]]; 


} 
-1

請記住,如果你正在使用的UINavigationController你必須做

UINavigationController *viewConNav = (UINavigationController *)self.presentingViewController; 
YourVC *viewCon = (YourVC *)viewConNav.topViewController;