2016-09-02 19 views
1

Я создал мероприятие, в котором, когда одно из текстовых полей щелкнуло его, появится дочерний элемент (диалоговое окно с предупреждением) со списком продуктов, но когда я нажму один элемент в списке, я не смогу его отобразить в текстовом файле предупреждение отклонено.Как передать данные с контроллера дочернего на родительский? in swift

это родительский вид

import Foundation 
import UIKit 

class ViewAward: UIViewController{ 

@IBOutlet var tfMCN: UITextField! 
@IBOutlet var tfAmount: UITextField! 
@IBOutlet var tfProduct: UITextField! 
@IBOutlet var tfTotal: UITextField! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let rightAddBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "Send", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ViewAward.searchTapped)) 

    self.navigationItem.setRightBarButtonItems([rightAddBarButtonItem], animated: true) 

    let state = String(ViewPopUpProduct.Product.ProductDescription) 
    print("My view state:"+state) 

    self.tfProduct.text = state 
    tfProduct.addTarget(self, action: #selector(ViewAward.productTapped), forControlEvents: UIControlEvents.TouchDown) 

} 

func searchTapped(sender:UIButton) { 

    let alertController = UIAlertController(
     title: "Award", 
     message:"Award successfully posted!", 
     preferredStyle: UIAlertControllerStyle.Alert) 
    alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) 

    self.presentViewController(alertController, animated: true, completion: nil) 
} 

func productTapped(textfield: UITextField){ 

    //tfProduct.endEditing(true) 
    tfProduct.resignFirstResponder() 

    let popOverVC = UIStoryboard(name:"Main",bundle:nil).instantiateViewControllerWithIdentifier("sbPopUpID") as! ViewPopUpProduct 

    self.addChildViewController(popOverVC) 

    popOverVC.view.frame = self.view.frame 

    self.view.addSubview(popOverVC.view) 

    popOverVC.didMoveToParentViewController(self) 

} 
} 

и это, когда пользователь нажал на из пунктов

import UIKit 

class ViewPopUpProduct: UIViewController { 

@IBOutlet var tableView: UITableView! 

var productDescription = ["Product 1","Product 2","Product 3"] 
var productID = ["prdct1","prdct2","prdct3"] 


// Global Variables 
struct Product { 
    static var ProductID = String() 
    static var ProductDescription = String() 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.showAnimate() 
    self.view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.4) 

    // Do any additional setup after loading the view. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

@IBAction func cancelPopUp(sender: AnyObject) { 
    self.removeAnimate() 
} 


func showAnimate() 
{ 
    self.view.transform = CGAffineTransformMakeScale(1.3, 1.3) 
    self.view.alpha = 0.0; 
    UIView.animateWithDuration(0.25, animations: { 
     self.view.alpha = 1.0 
     self.view.transform = CGAffineTransformMakeScale(1.0, 1.0) 
    }); 
} 

func removeAnimate() 
{ 
    UIView.animateWithDuration(0.25, animations: { 
     self.view.transform = CGAffineTransformMakeScale(1.3, 1.3) 
     self.view.alpha = 0.0; 
     }, completion:{(finished : Bool) in 
      if (finished) 
      { 
       self.view.removeFromSuperview() 
      } 
    }); 
} 

//Mark - Table View 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.productID.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell",forIndexPath: indexPath) as! ProductViewCell 

    cell.productLabel.text = productDescription[indexPath.row] 

    return cell 
} 

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

    tableView.deselectRowAtIndexPath(indexPath, animated: true) 

    Product.ProductID = String(productID[indexPath.row]) 
    Product.ProductDescription = String(productDescription[indexPath.row]) 

    self.removeAnimate() 

} 

} 
+1

Вы можете добавить свой код и тип предупреждения, которое вы указали. –

+1

Попробуйте обновить свой вопрос с помощью некоторого кода, который вы внедрили, что даст нам правильное представление о том, что вы делаете. На основании этого вы предложите лучший ответ. – Tuhin

+0

неожиданныйNil я уже обновляю вопрос –

ответ

1

Вы можете использовать протоколы/делегировать

Вот очень очень простое объяснение, не бс: https://www.youtube.com/watch?v=guSYMPaXLaw

Или в вашей ситуации вы можете также использовать NSNotificationCenter

Вы можете сделать что-то вроде этого :

Контролер вида «отправитель» будет делать

let nc = NSNotificationCenter.defaultCenter() 
nc.postNotificationName("printValue", object: nil, userInfo: ["value" : "Pass Me this string"]) 

Затем контроллер приемника может прослушивать уведомление.

let nc = NSNotificationCenter.defaultCenter() 
nc.addObserver(self, selector: #selector(printValue), name: "printValue", object: nil) 

func printValue(notification:NSNotification) { 
    let userInfo:Dictionary<String,String> = notification.userInfo as! Dictionary<String,String> 
    let item = userInfo["value"]! as String 

    print(item,self) 
} 
+1

спасибо, но моя проблема в том, что я не использовал segue. Я загружаю дочерний вид и в этом дочернем представлении есть таблицы элементов, когда я нажал на элемент, я захвачу пропущенный элемент и отклоню вид ребенка и отобразит захваченные данные в текстовом поле –

+0

'NSNotification' - самый худший и самый дорогой способ для связанных контроллеров. Протокол/делегат намного лучше (и закрытие, поскольку обратные вызовы имеют современное состояние). – vadian

+0

спасибо, сэр !! –

4

Есть несколько способов, с помощью которых можно реализовать функции обратного вызова для передачи данных.

  • Делегат
  • Использование блока CallBack
  • Сообщение Извещение

Но я бы предложил использовать делегат, который является лучшим способом, Post Notification является также способ, но я не хотят отдавать предпочтение.

+0

не могли бы вы помочь мне с кодом? Я уже назначаю глобальную переменную, но она обновляет значение текстового поля, когда представление перезагружается не тогда, когда ребенок уволен. –

4

Обычно я использую закрылки для этой цели. Намного проще и компактнее, чем делегаты:

class MainViewController: UIViewController { 

    func showChildViewController() { 
     guard let vc = storyboard?.instantiateViewControllerWithIdentifier("ChildViewController") as? ChildViewController else { 
      return 
     } 
     vc.didSelectItem = { [weak self](item) in 
      if let vc = self { 
       // Do something with the item. 
      } 
     } 
     presentViewController(vc, animated: true, completion: nil) 
    } 

} 

class ChildViewController: UIViewController { 

    var didSelectItem: ((item: Item) -> Void)? 

    @IBAction func buttonPressed() { 
     didSelectItem?(item: <#your item goes here#>) 
    } 

} 
+0

я использовал это, чтобы показать ребенка 'Код' функ productTapped (текстовое поле: UITextField) { //tfProduct.endEditing(true) tfProduct.resignFirstResponder() пусть popOverVC = UIStoryboard (название: "Main" , bundle: nil) .instantiateViewControllerWithIdentifier ("sbPopUpID") как! ViewPopUpProduct self.addChildViewController (popOverVC) popOverVC.view.frame = self.view.frame self.view.addSubview (popOverVC.view) popOverVC.didMoveToParentViewController (само) } 'Код' –

+0

@JosephVincentMagtalas Я дал вам общее представление о том, как добиться этого. Пожалуйста, адаптируйте свой ответ к вашим потребностям самостоятельно. –

+0

Где находится Товар? in 'var didSelectItem: ((item: Item) -> Void)? ' im new для разработки приложений спасибо –

2
  1. Моего первое предпочтение должно быть пользовательским делегатом, который является более быстрым и совершенным. (Если вы можете использовать закрытие в качестве обратных вызовов, то это должно быть идеально. Выбор делегата для объяснения с помощью вашего кода немного.)

  2. Пожалуйста, избегайте использования NSNotificationCenter настолько, насколько это возможно, потому что есть так много вещей, при использовании этого и немного медленнее, чем делегаты. Вы можете легко попасть в баги с этим тоже.

Теперь вот мой код.

1. Настройка детского монитора.

// TrendingProductPageViewController.swift 
    // buddyiOSApp 
    // 
    // Created by Tuhin Samui on 5/21/16. 
    // Copyright © 2016 Buddy. All rights reserved. 
    // 

    import UIKit 

    protocol TrendingProductsCustomDelegate: class { //Setting up a Custom delegate for this class. I am using `class` here to make it weak. 
     func sendDataBackToHomePageViewController(categoryToRefresh: String?) //This function will send the data back to origin viewcontroller. 
    } 


    class TrendingProductPageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NetworkReachabilityDelegate { 

     @IBOutlet weak var productListTableView: UITableView! //Having a tableview outlet here from storyboard itself. BTW not going to explain with tableView delegate and datasource, Sorry..:(

     weak var customDelegateForDataReturn: TrendingProductsCustomDelegate? //Please use weak reference for this to manage the memory issue. 


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
      let rowNumberFromTable: Int = indexPath.row //Getting the index of the selected cell. 
      let dataToSendBack = moreMenuTableData[rowNumberFromTable] as! String //This is an array which contains the data for the tableview. Getting the exact data which is selected on the table. 
      customDelegateForDataReturn?.sendDataBackToHomePageViewController?(dataToSendBack) //Now sending the selected data back to parent viewController using the custom delegate which I made before.     presentingViewController?.dismissViewControllerAnimated(true, completion: nil) //Dismissing the viewController here. 
    } 

2.Здесь приведен код родительского ViewController.

class HomePageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TrendingProductsCustomDelegate, UINavigationControllerDelegate{ //Adding the protocol here as `TrendingProductsCustomDelegate` 

@IBAction func topTrendingProductsBtnAction(sender: UIButton) { //Normal IBAction of UIButton as you are using. 
     let trendingProductsPageForAnimation = storyboard!.instantiateViewControllerWithIdentifier("showTrendingProductpage") as! TrendingProductPageViewController //You can understand this right. Same as yours. 
     trendingProductsPageForAnimation.customDelegateForDataReturn = self //Setting up the custom delegate for this class which I have written on the presenting class. 
     trendingProductsPageForAnimation.modalPresentationStyle = UIModalPresentationStyle.FullScreen 
     presentViewController(trendingProductsPageForAnimation, animated: true, completion: nil) //Same as yours. 
    } 


func sendDataBackToHomePageViewController(categoryToRefresh: String?) { //Custom delegate function which was defined inside child class to get the data and do the other stuffs. 
     if categoryToRefresh != nil { 
      print("Got the data is \(categoryToRefresh)") 
     } 
    } 

} 

Надеюсь, это помогло. Извините за любую ошибку.

+0

спасибо, я попробую –