[英]passing data from UItableviewController to UItableViewcell
[英]Swift remove data stored in UITableViewController from UITableViewCell
我有一個自定義類,該類擴展了UIViewController並包含一個表視圖,並帶有一個數組,該數組存儲填充表視圖的數據。 對於我的自定義單元格,我有一個按鈕,當按下該按鈕時,應從表格視圖中刪除該單元格。 但是,我還沒有找到一種方法可以從表視圖控制器中的數組中刪除數據,並從單元格的類中重新加載數據。 我在類似的帖子中看到的一些答案建議使用通知或委派,但是由於我的應用程序(標簽控制器)的結構以及我已經將通知用於其他功能,因此前者效率低下,我不知道如何在這種情況下使用后者。 這是自定義單元格類的代碼:
class CustomCell: UITableViewCell {
@IBOutlet var label: UILabel!
@IBOutlet var removeButton: UIButton!
@IBAction func remove(sender: AnyObject) {
// don't know what to put here
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
這是表視圖控制器類:
class CustomController: UIViewController, UITableViewDataSource {
@IBOutlet var table: UITableView!
var data: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = table.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
// put content in
return cell
}
}
數組data
是我想從CustomCell
remove
訪問的data
。 我最近得到的是在CustomCell
使用self.superview.superview.superview
,它返回CustomController
控制的視圖。 但是,如果不實例化一個新實例,就無法獲得CustomController
實例。 如何從CustomCell
類修改CustomController
的變量?
在您的自定義單元格中添加此
class CustomCell: UITableViewCell {
var customControllerReference: CustomController?
}
並在cellForRowAtIndexPath中的自定義控制器中添加此
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = table.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
cell.customControllerReference = self
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.