2017-06-08 22 views
1

我有一個UITableView的自定義單元格。當用戶點擊單元中的按鈕時,用戶必須從當前的ViewController1導航到ViewController2。我已經定義了自定義單元類中的按鈕動作。但需要回電ViewController1快速關閉可以用於2級之間的通信嗎?

我嘗試使用closure類似於我們如何在目標C中使用塊。它在同一類中使用時工作正常。但在兩個不同的類中使用時會出錯。

+0

發表你已經嘗試過(一些代碼)。有可能在2個VC之間通過關閉。 – Brduca

+0

您需要使用協議。我將很快發佈答案 –

+0

是的,使用代表和協議或通知交替! – LinusGeffarth

回答

0

您需要在那裏使用委託協議。

例子:協議發送UserItem當事情發生在cell

protocol TappedUserDelegate: class { 
    func userInfoTapped(_ tappedUser: UserItem?) 
} 

在你controller

extension Controller: TappedUserDelegate { 
    func userInfoTapped(_ user: UserItem?) { 
     // user is tapped user in cell  
    } 
} 

在你tableView FUNC:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    // ........ 
    cell.delegateUserTaps = self // for user info taps to perform segue 
    // ........ 
} 

在您的自定義cell

class CustomCell: UITableViewCell { 
    weak var delegateUserTaps: TappedUserDelegate? // for sending user info 

    // ........ 
    func userInfoTapped() { 
     delegateUserTaps?.userInfoTapped(userItem) // <- send data to controller 
    } 
} 

userInfoTapped將被調用,您的控制器功能將與該用戶進行。

我給你一個主意。

希望它有幫助

+0

謝謝。因爲我沒有15點聲望,所以我無法提升你的答案。 – ABM

+0

@ABM如果有幫助,你可以接受。按寒鴉 –