2016-05-25 31 views
0

我有我嵌套UICollectionView的UIViewController。對於UICollectionViewCell我創建的子類「MyCell」Swift - 從自定義單元格傳遞數據

我在每個單元格中都有UITextField,並且希望將數據從文本字段傳遞迴父級視圖控制器以更新標籤。我發現更新標籤的唯一方法是使用NSNotificationCenter和調用方法來執行更改並從NSObject類訪問數據。然而,它返回零值

的ViewController:

var dataModel = DataModel() // NSObject class 

override func viewDidLoad() { 
    super.viewDidLoad() 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.updateResultLabel(_:)), name:"update", object: nil) 
} 

func updateResultLabel(notification: NSNotification){ 

    resultLabel.text = dataModel.cellData 
    print(dataModel.cellData) 
} 

了myCell:

class MyCell: UICollectionViewCell { 

    @IBOutlet weak var txtField: UITextField! 

    @IBAction func updateLabel(){ 

     let cell: UICollectionViewCell = txtField.superview!.superview as! UICollectionViewCell 
     let table: UICollectionView = cell.superview as! UICollectionView 
     let textFieldIndexPath = table.indexPathForCell(cell) 

     let dataModel = DataModel() 
     dataModel.cellData = txtField.text! 

     print("txtField: \(txtField.text), row: \(textFieldIndexPath?.row)") 

     NSNotificationCenter.defaultCenter().postNotificationName("update", object: nil) 
    } 
} 

的作用是直接從的UITextField觸發 - 的valueChanged在故事板

的DataModel:

import Foundation 

class DataModel: NSObject { 

    var cellData: String? 

} 

ViewController方法「updateResultLabel」的「print」方法顯示「nil」。我顯然做錯了什麼,可能不會在某處初始化字符串。或者也許還有另一種方式,我可能沒有遇到過呢?

如何將數據從「MyCell」傳遞給「ViewController」並更新方法?

謝謝

回答

1

我會在視圖控制器使用UITextfieldDelegate並從細胞文本框的視圖 - 控制設置委託。

你在哪裏填充單元,你可以寫:

cell.txtField.delegate = self 

您現在可以實現委託功能控制器

+0

謝謝,就像魅力!我發現有關實現委託[這裏]的線程(http://stackoverflow.com/questions/29913066/how-to-access-the-content-of-a-custom-cell-in-swift-using-button-tag) – Alessign

相關問題