2014-11-25 4 views
0

Я пробовал другие методы делегирования и протоколов для передачи данных между модальными представлениями и родительской кнопкой просмотра, они не работают для меня. Это, очевидно, потому, что я внедряю их неправильно.delegate modal view swift

У меня есть контроллер родительского представления, у которого есть tableviewcell, который в правильной детализации расскажет вам ваш выбор из модального вида. Модальное представление - это другой вид таблицы, который позволяет вам выбрать ячейку, которая обновляет правильную деталь и отменяет модальное представление. Все работает, за исключением фактической передачи данных.

Спасибо заранее! :)

Вот мой код контроллера родительского вида:

class TableViewController: UITableViewController, UITextFieldDelegate { 

//Properties 

var delegate: transferData? 

//Outlets 
@IBOutlet var productLabel: UILabel! 
@IBOutlet var rightDetail: UILabel! 





override func viewWillAppear(animated: Bool) { 
    println(delegate?.productCarrier) 
    println(delegate?.priceCarrier) 
    if delegate?.productCarrier != "" { 
     rightDetail.text = delegate?.productCarrier 
     productLabel.text = delegate?.productCarrier 
    } 
} 


override func viewDidLoad() { 
    super.viewDidLoad() 

} 



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

// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // #warning Potentially incomplete method implementation. 
    // Return the number of sections. 
    return 5 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete method implementation. 
    // Return the number of rows in the section. 
    return 1 
} 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    tableView.deselectRowAtIndexPath(indexPath, animated: true) 
} 



} 

Код для контроллера представления модели и протокола:

protocol transferData { 
var priceCarrier: Double { get set } 
var productCarrier: String { get set } 
} 

class ProductsDetailsViewController: UITableViewController, transferData { 
//Properties 

var priceCarrier = 00.00 
var productCarrier = "" 


//Outlets 


//Actions 

@IBAction func unwindToViewController(segue: UIStoryboardSegue) { 
    self.dismissViewControllerAnimated(true, completion: nil) 


} 


override func viewDidLoad() { 
    super.viewDidLoad() 
    populateDefaultCategories() 

    // Uncomment the following line to preserve selection between presentations 
    // self.clearsSelectionOnViewWillAppear = false 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    // self.navigationItem.rightBarButtonItem = self.editButtonItem() 
} 

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

// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // #warning Potentially incomplete method implementation. 
    // Return the number of sections. 
    return Int(Category.allObjects().count) 
} 


override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return (Category.allObjects()[UInt(section)] as Category).name 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete method implementation. 
    // Return the number of rows in the section. 

    return Int(objectsForSection(section).count) 


} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    var cell:ProductListCell = tableView.dequeueReusableCellWithIdentifier("productCell", forIndexPath: indexPath) as ProductListCell 

    let queriedProductResult = objectForProductFromSection(indexPath.section, indexPath.row) 

    cell.name.text = queriedProductResult.name 
    cell.prices.text = "$\(queriedProductResult.price)" 

return cell 


} 

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

    let indexPath = self.tableView.indexPathForSelectedRow()! 

    let product = objectForProductFromSection(indexPath.section, indexPath.row) 

    let PVC: TableViewController = TableViewController() 

    println("didSelect") 
    productCarrier = product.name 
    priceCarrier = product.price 

    println(productCarrier) 
    println(priceCarrier) 


    self.dismissViewControllerAnimated(true, completion: nil) 


} 

ответ

0

Я думаю, что для передачи данных, вы должны использовать Segue как:

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

let indexPath = self.tableView.indexPathForSelectedRow()! 
let product = objectForProductFromSection(indexPath.section, indexPath.row) 

println("didSelect") 
productCarrier = product.name 
priceCarrier = product.price 

println(productCarrier) 
println(priceCarrier) 

self.performSegueWithIdentifier("displayYourTableViewControllerSegue", sender: self) 

}

, а затем переопределить prepareForSegue функцию:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    var controller = segue.destinationViewController as TableViewController 
    controller.rightDetail.text = "\(self.priceCarrier)" 
    controller.productLabel.text = self.productCarrier 
    } 
+0

Так какой код идет в какой файл извините? Спасибо, хотя @Florian – Tomblasta

+0

Извините, я реализовал это, и он все еще не работает. Есть ли способ сделать это с делегатами? @thelion – Tomblasta

+0

Весь этот код отправляется в файл Контейнера. Что не сработало? Потому что использование делегата для передачи данных кажется странным. Для меня делегат должен использоваться для функций обратного вызова (например). Кроме того, вам придется создавать протокол каждый раз, когда вам нужно будет передавать данные. – Florian