簡體   English   中英

呈現UIViewController並將數據傳遞回呈現視圖

[英]Present UIViewController and pass back data to presenting view

我有一個應用程序,要求您在模式UIViewController中的多個位置選擇數據。 像這樣想象:您想查看一個餐廳是否有任何可用的表->彈出一個模式UIViewController ,您可以在列表中選擇一個餐廳,然后將其關閉,並將數據傳遞回呈現視圖。 您想查看相關的餐廳->彈出一個模式UIViewController ,您可以在其中選擇列表中的餐廳,然后將其關閉,並將數據傳遞回呈現視圖。 等等。

現在,我可以通過在呈現視圖中設置RestaurantViewController.delegate = self來做到這一點。 然后,我可以稱呼類似[delegate pickedRestaurant:restaurant]; ,但我不喜歡這樣的泛泛。

還有其他方法可以通過數據回調來呈現UIViewController嗎?

如您在問題中所指出的,當您要將數據傳遞回呈現的UIViewController時, delegate設計模式很有用。 如果您不想NSNotificationCenter委托設計模式,那么也許可以使用NSNotificationCenter 它沒有太多的內存,它會觸發一個應用程序范圍的廣播,可以由NSObserver接收,您可以將其放置在呈現的UIViewController (假設呈現的UIViewController仍在內存中。例如,代碼可以看起來與此類似的東西:

ViewControllerA.swift

override func viewDidLoad(){
 super.viewDidLoad()
 let notifCenter = NSNotificationCenter.defaultCenter()
 notifCenter.addObserver(self, selector: #selector(ViewControllerA.methodToTrigger), name: "pickedRestaurantNoti", object: nil)
}

func methodToTrigger(notification:NSNotification){

    let userInfo:Dictionary<String,String!> = notification.userInfo as Dictionary<String,String!>
    let pickedRestaurantFromB = userInfo["pickedRestaurant"]
    // pickedRestaurantFromB should have the value of "Restaurant 1"
    // handle that value now that you have gotten it

}

ViewControllerB.swift

func someMethod(){
 let notifCenter = NSNotificationCenter.defaultCenter()
 notifCenter.postNotificationName("pickedRestaurantNoti",
                        object:nil,
                        userInfo:["pickedRestaurant":"Restaurant 1"])
}

假設有兩個vc A和B。

將Bh中的物業添加為

@property A *aobjet

和財產在作為

@property NSString *str;

當您從Am提出這樣的B呼叫時

B *b = [B alloc]init];
[self presentViewController:B animated:YES completion:^{
  b.aobject = self;

}];

然后在從Bm彈出之前設置A的屬性,例如字符串,

self.aobject.str = @"your data";
 [[self.navigationController popViewController animated:YES];

如果有的話請避免語法錯誤,因為我在這里輸入了錯誤!

暫無
暫無

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

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