![](/img/trans.png)
[英]Populate UITableView Custom Cell with NSMutableArray data - Swift
[英]Troubleshooting Custom UITableView Cell [Swift]
我在故事板中創建了一個自定義UITableView單元格,如下所示:
我將其連接到我的UITableViewCell類,如下所示:
導入UIKit
class StatusCell: UITableViewCell {
@IBOutlet weak var InstrumentImage: UIImageView!
@IBOutlet weak var InstrumentType: UILabel!
@IBOutlet weak var InstrumentValue: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
最后,我嘗試從UIViewController初始化UITableView,如下所示:
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var TableView: UITableView!
let Items = ["Altitude","Distance","Groundspeed"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.Items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: StatusCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as StatusCell!
cell.InstrumentType?.text = Items[indexPath.row]
cell.InstrumentValue?.text = "150 Km"
cell.InstrumentImage?.image = UIImage(named: Items[indexPath.row])
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
但是,當我嘗試運行程序時,出現EXC_BAD_INSTRUCTION錯誤:
我做錯了什么? 任何幫助,將不勝感激!
調試器輸出顯示cell
為nil
,這意味着無法實例化。 此外,您正在強制展開可選項(使用!
),這會導致應用程序在nil
值上崩潰。
嘗試像這樣更改您的cellForRowAtIndexPath
方法(注意dequeueReusableCellWithIdentifier
方法):
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as StatusCell
cell.InstrumentType.text = Items[indexPath.row]
cell.InstrumentValue.text = "150 Km"
cell.InstrumentImage.image = UIImage(named: Items[indexPath.row])
return cell
}
假設您的自定義tableViewCell類已正確設置並且插座已綁定,則無需檢查可選項。
在let cell = ...
行上放置一個斷點,然后逐步執行代碼。 檢查cell
是否已初始化並且不是nil
。
並且請:不要將大寫字母的名稱用於屬性和變量(出口, Items
數組等),因為大寫字母的名稱用於類,結構等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.