2016-05-25 14 views
0

私はUICollectionViewをネストしたUIViewControllerを持っています。 UICollectionViewCellのサブクラス "MyCell"を作成しましたSwift - カスタムセルからデータを渡す

私は各セルにUITextFieldを持ち、テキストフィールドのデータをペアレンダリングビューコントローラに戻してラベルを更新したいと考えています。ラベルを更新する唯一の方法は、NSNotificationCenterを使用してメソッドを呼び出して変更を実行し、NSObjectクラスからデータにアクセスすることです。

import Foundation 

class DataModel: NSObject { 

    var cellData: String? 

} 
: - :

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:ストーリーボード内のvalueChanged

のDataModel

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の直接トリガされるが、それは

のViewControllerゼロ値を返します

ViewControllerのメソッドの "print"メソッド "updateResultLabel"は "nil"を示します。私は明らかに間違ったことをしています、おそらくどこかで文字列を初期化していないでしょう。それとも、私はおそらくまだ出会っていない別の方法がありますか?

「MyCell」のデータを「ViewController」に渡して更新するにはどうすればよいですか?

あなたは

答えて

1

私はViewControllerをでUITextfieldDelegateを使用して、細胞のテキストフィールドでのViewControllerからデリゲートを設定しますありがとうございました。あなたが書くことができ、細胞移入

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

関連する問題