2017-02-24 61 views
-1

我在過去幾天學習iOS編程,所以我對這個技術很陌生。我正在構建簡單的應用程序,我正在使用其中包含EventCell的集合視圖。每個EventCell都有一個UIButton,EventCell具有uniq值(來自JOSN API響應的ID)。我需要將該值傳遞給調用新ViewController的委託。我已經安裝的委託方法,它工作正常,只是發現瞭如何通過按鈕價值的解決方案點擊如何將UIButton的值傳遞給在collectionViewCell中委託的值?

PS:我不是用故事板

**EventCell.swift** 

lazy var leaderboardButton: UIButton = { 
    let leaderboardBtn = UIButton(type: .system) 
    leaderboardBtn.setTitle("LeaderBoard", for: .normal) 
    leaderboardBtn.addTarget(self, action: #selector(handleLeaderBoardClick), for: .touchUpInside) 
    leaderboardBtn.tintColor = .white 
    return leaderboardBtn 
}() 

weak var delegate: HomeControllerDelegate? 
func handleLeaderBoardClick() { 
    // need to get uniq value and pass here.... 
    delegate?.clickOnLeaderBoard() 
} 

回答

-1

更改您的功能,包括參數:

func handleLeaderBoardClick(_ sender: UIButton) { 
    // need to get uniq value and pass here.... 
    delegate?.clickOnLeaderBoard() 
} 

更新的選擇:

leaderboardBtn.addTarget(self, action: #selector(handleLeaderBoardClick(_:)), for: .touchUpInside) 

現在你可以執行senderleaderboardButton之間的比較以查看它們是否相同。

+0

我明白了你的意思,但是如何獲得這個uniq ID?在那個功能? –

+0

你可以從單元中獲得ID,對嗎?檢查按鈕的超級視圖,這應該是你的單元格。 –

0

如果您需要將該ID值傳遞給委託對象,您的案例是您的ViewController - 那麼您需要修改HomeControllerDelegate協議中的clickOnLeaderboard函數。

修改它並將EventCell的ID作爲附加參數傳遞給它。

delegate?.clickOnLeaderBoard(cellID)

另外,不要忘記更新在視圖控制器類函數簽名。

0

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)超載

補充一點:

cell.yourButton.tag = indexPath.row 
cell.yourButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside) 

你應該在你的UIViewController buttonClicked(sender:)

buttonClicked(sender:){ 
tag = sender.tag 
// you can use this tag to change your view controller 

}