2016-05-25 96 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

相关问题