2017-02-10 6 views
0

イベントの別のビューコントローラでコレクションビューを再読み込みするデリゲート関数を作成しようとしています。デリゲート関数で使用するViewControllerの正しいインスタンスを取得

この目的のために、私はプロトコルを定義し、クラス内にデリゲートを設定し、単純なデリゲート関数を設定しました。

// define the delegate for use 
weak var reloadJourneyDelegate: ReloadCollectionDelegate? 

// reload the collection view in JourneyViewController 
let JVC = self.viewController.storyboard!.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController 
self.reloadJourneyDelegate = JVC 
self.reloadJourneyDelegate?.reloadCollectionViewFromDelegate() 

プリント(JVC):

JourneyViewController: 0x7fc7f7c55bf0 

プリント(自己) - JourneyViewController(のviewDidLoad)から:

protocol ReloadCollectionDelegate: class { 
    func reloadCollectionViewFromDelegate() 
} 


class JourneyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITabBarControllerDelegate, UIScrollViewDelegate, ReloadCollectionDelegate { 

    // delegate function from downloadCollectionController to relaod collection 
    func reloadCollectionViewFromDelegate() { 
     // simply call the reload function 
     reloadCollection() 
    } 

そして、上記の関数を呼び出すことになる私のクラスで

JourneyViewController: 0x7fc7f7e2db10 

同じView Controllerの異なるインスタンス。

これを定義して正しいインスタンスを持ち、UIを変更する方法を教えてください。

おかげ

+0

あなたがのviewDidLoadを呼び出しているの? –

+0

JourneyViewControllerクラスのviewDidload()にselfを出力しています – Pippo

答えて

1

この行は、あなたがJourneyViewControllerの元のインスタンスに戻って参照する方法を持っている必要がありますJourneyViewController

self.viewController.storyboard!.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController 

の新しいインスタンスを作成します。どちらかそれにまたは両方のビューコントローラがJourneyViewControllerは、別のビューコントローラの親であるような階層にある場合指し示す性質持つことによって:

class ViewControllerA: UIViewController { 
    override viewDidLoad() { 
     let button = UIButton(frame: CGRect(x: self.view.bounds.width/2, y: 400, width: 50, height: 50)) 
     button.backgroundColor = UIColor.black 
     button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) 
     self.view.addSubview(button) 
    } 

    func buttonPressed() { 
     let journey = self.parent as! JourneyViewController 
     journey.reloadCollection() 
    } 
} 
関連する問題