簡體   English   中英

UITableView Swift 2中的CustomCell

[英]CustomCell in UITableView Swift 2

我已經創建了一個UITableView,並且想要動態創建單元格來保存諸如名稱,持續時間和價格之類的信息。

我有以下代碼:

class MyCustomTableViewCell: UITableViewCell {
    @IBOutlet weak var price: UILabel!
}

class TableViewController: UITableViewController {
    var data = [["name1","amount1","duration1"],["Name2","amount2","duration2"],["name3","amount3","duration3"]]


override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomTableViewCell", forIndexPath: indexPath) as! MyCustomTableViewCell

    cell.textLabel?.text = "\(data[indexPath.row][0])"
    cell.detailTextLabel?.text = "\(data[indexPath.row][1])"
    cell.price.text = "\(data[indexPath.row][2])"
    return cell
}

}

我在情節提要板上出現以下錯誤:

從TableViewController到UILabel的價格出口無效。 插座不能連接到重復的內容。

我了解錯誤的含義,但是我認為MyCustomTableViewCell類意味着price變量是動態的,因此不嘗試重復靜態內容。

任何幫助,將不勝感激 :)

在此處輸入圖片說明

我從Askash那里得到了這個答案,但是我的代碼似乎有些混亂,所以我以為id會發布我的答案,以防其他人對此有麻煩。

步驟1.確保使用以下代碼創建TableViewController並確保在情節提要板上設置了它:

class TableViewController: UITableViewController {
var data = [["name1","amount1","duration1"],["Name2","amount2","duration2"],["name3","amount3","duration3"]]


override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell

    cell.textLabel?.text = "\(data[indexPath.row][0])"
    cell.detailTextLabel?.text = "\(data[indexPath.row][2])"
    cell.price.text = "£\(data[indexPath.row][2])"
    return cell
}

}

在故事板上,單擊TableViewController,單擊“顯示身份檢查器”,然后在類部分中粘貼“ TableViewController”: 在此處輸入圖片說明

步驟2創建一個新的TableViewCell類。 -轉到“文件”>“新建”>“文件...”>“ IOS源”>“可可觸摸類”>“下一步”,並創建一個包含UITableViewCell子類的TableViewCell類: 在此處輸入圖片說明

步驟3將TableViewCell分配給原型單元並設置恢復ID。

單擊情節提要中的原型單元,單擊顯示“屬性檢查器”,然后將“ TableViewCell”粘貼到類部分以及標識符類型“單元”中: 在此處輸入圖片說明

步驟4在“ TableViewCell”類中創建標簽“ Price”的出口。 (使用Ctrl +拖動)並將其命名為“價格”。

TableViewCell中的代碼應如下所示:

TableViewCell類:UITableViewCell {

@IBOutlet weak var price: UILabel!


override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM