[英]Subclass UIButton to save Data?
我想知道是否有任何問題擴展UIButton以獲得我的數據的參考?
例如,我有一個表視圖,每當用戶點擊一個單元格時,我需要向用戶提供該特定單元格的數據。
數據保存在數組中,數組索引保存在UIButton標記中,但隨着我的數組更新,將提供錯誤的索引。 所以我試圖做的是擴展一個uibutton然后有一個變量來保存我的模型。
這個想法很好但是由於我沒有真正體驗過swift,我想知道做這樣的事情有什么缺點和問題。
您不需要將index
保存為Button的標記。 將評論中指出的UIButton子類化為Sneak顯然是一個非常糟糕的主意。 最重要的是,在UIComponent
中保存模型是災難設計。
你可以采取多種方式。 一個我發現整潔:
第1步:
為自定義單元格創建一個類。 讓我們說MyCollectionViewCell
。 因為你的Cell里面有一個按鈕,你應該在Cell里面創建按鈕的IBAction
。
class MyCollectionViewCell: UICollectionViewCell {
@IBAction func myButtonTapped(_ sender: Any) {
}
}
第2步:
讓我們聲明一個協議,我們將用它與tableView / CollectionView的dataSource進行通信。
protocol MyCollectionViewCellProtocol : NSObjectProtocol {
func buttonTapped(for cell : MyCollectionViewCell)
}
第3步:
讓我們在MyCollectionViewCell中創建一個屬性
weak var delegate : MyCollectionViewCellProtocol? = nil
在第3步之后,您的MyCollectionViewCell類應如下所示
protocol MyCollectionViewCellProtocol : NSObjectProtocol {
func buttonTapped(for cell : MyCollectionViewCell)
}
class MyCollectionViewCell: UICollectionViewCell {
weak var delegate : MyCollectionViewCellProtocol? = nil
@IBAction func myButtonTapped(_ sender: Any) {
self.delegate?.buttonTapped(for: self)
}
}
第四步:
在您的tableView的CellForRowAtIndexPath或CollectionView的sizeForItemAtIndexPath確認傳遞ViewController作為單元格的委托。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : MyCollectionViewCell = //deque your cell
(cell as! MyCollectionViewCell).delegate = self
}
第5步:
現在讓ViewController確認協議
class YourViewController: UIViewController,MyCollectionViewCellProtocol {
第6步:
最后在VC中實現方法
func buttonTapped(for cell: MyCollectionViewCell) {
let indexPath = self.collectionView?.indexPath(for: cell)
//access array now
}
PS:
很抱歉雖然我知道你正在使用TableView,但我趕緊為CollectionView編寫代碼,但代表卻相同:)我希望你能理解邏輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.