我使用的Xcode 7.0呼籲,斯威夫特2的cellForRowAtIndexPath不是從自定義類
基本上,我想創建一個自定義類,將建立一個UITable
,然後在ViewController
我提出的一個新對象該表並將其加載到self.view中;
我遇到的問題是函數func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
根本沒有在自定義類中被調用。我一直在尋找3天的解決方案,我已經嘗試重新編譯應用程序並編寫代碼幾次,但沒有運氣。
請注意,如果我在ViewController.swift文件中使用相同的代碼(這是生成表格所需的所有內容;不包括init函數等),它可以正常工作。
我知道問題出在cellForRowAtIndexPath
函數上,因爲它在運行時不會打印出我在代碼塊中設置的語句。所有其他函數都被調用,但由於某種原因,這不會被調用。不知道我在這裏忽略了什麼。任何幫助,將不勝感激。提前致謝。
class sideTest: NSObject, UITableViewDelegate, UITableViewDataSource {
let tesTable: UITableView = UITableView()
var items: [String]?
var mView: UIView = UIView()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("The number of rows is: \(self.items!.count)")
return self.items!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("\nLets create some cells.")
let sCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
sCell.textLabel?.text = self.items![indexPath.row]
sCell.textLabel?.textColor = UIColor.darkTextColor()
return sCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
func tblSetup() {
self.tesTable.frame = CGRectMake(0, 0, 320, mView.bounds.height)
self.tesTable.delegate = self
self.tesTable.dataSource = self
self.tesTable.backgroundColor = UIColor.cyanColor()
// load cells
self.tesTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.tesTable.reloadData()
print("Currenlty in tblSetup.\nCurrent rows is: \(self.items!.count)")
}
//Init
override init() {
super.init()
self.items = nil
self.tblSetup()
}
init(sourceView: UIView , itemListAsArrayString: [String]) {
super.init()
self.items = itemListAsArrayString
self.mView = sourceView
self.tblSetup()
}
}
這是來自ViewController.swift的代碼;請注意,表被建立,但這些細胞不填充,即使我手動做進入小區信息:sCell.textLabel?.text = "test cell"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myTable: sideTest = sideTest(sourceView: self.view, itemListAsArrayString: ["Cell 1", "Cell 2", "Cell 3"])
self.view.addSubview(myTable.tesTable)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
同樣,任何幫助是極大的讚賞。謝謝。
你應該使用'init(frame frame:CGRect,style style:UITableViewStyle)''UITableView'的指定初始值設定項''但我不確定這會有什麼不同。 – Sulthan
你的類是否被設置爲表視圖的數據源? – quellish