【发布时间】:2016-05-25 20:12:01
【问题描述】:
我有 UIViewController,我在其中嵌套了 UICollectionView。对于 UICollectionViewCell 我创建了子类“MyCell”
我在每个单元格中都有 UITextField,并希望将文本字段中的数据传递回父视图控制器以更新标签。我发现更新标签的唯一方法是使用 NSNotificationCenter 并调用方法来执行更改并从 NSObject 类访问数据。但是,它返回 nil 值
视图控制器:
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)
}
我的细胞:
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
数据模型:
import Foundation
class DataModel: NSObject {
var cellData: String?
}
ViewController 方法“updateResultLabel”中的“print”方法显示“nil”。我显然做错了什么,可能没有在某处初始化字符串。或者可能还有另一种我还没有遇到过的方法?
请问如何将数据从“MyCell”传递到“ViewController”并更新方法?
谢谢
【问题讨论】:
标签: ios swift uicollectionviewcell subclassing