【问题标题】:Swift - Passing data from custom cellSwift - 从自定义单元格传递数据
【发布时间】: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


    【解决方案1】:

    我会在视图控制器中使用 UITextfieldDelegate,并在单元格文本字段中设置来自视图控制器的委托。

    你可以在哪里填充你可以写的单元格:

    cell.txtField.delegate = self
    

    您现在可以在控制器中实现委托功能

    【讨论】:

    • 谢谢,很有魅力!我找到了关于实现委托here的线程
    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多