[英]Multiple Custom Cells in TableViewController
在這個還算新。 我試圖將3個自定義單元格填充到TableViewController中。
我已經設法(在幫助下)順利加載了2個。 這是我用於2的代碼:
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row % 2 == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell") as! FirstTableViewCell
cell.artImageView.image = UIImage(named: "art")
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell") as! SecondTableViewCell
cell.kidsImageView.image = UIImage(named: "kids")
return cell
}
當我嘗試添加第三行時,這是我遇到麻煩的地方。 這是我正在使用的代碼:
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row % 3 == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell") as! FirstTableViewCell
cell.artImageView.image = UIImage(named: "art")
return cell
} else if {
let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell") as! SecondTableViewCell
cell.kidsImageView.image = UIImage(named: "kids")
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("ThirdCell") as! ThirdTableViewCell
cell.pastaImageView.image = UIImage(named: "pasta")
return cell
}
}
任何幫助都會很棒。 格拉西亞斯。
您的問題從這一行開始
if indexPath.row % 3 == 0 {
如果您確實希望將單元1、2、3布局,則可以執行以下操作:
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell") as! FirstTableViewCell
cell.artImageView.image = UIImage(named: "art")
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell") as! SecondTableViewCell
cell.kidsImageView.image = UIImage(named: "kids")
return cell
} else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier("ThirdCell") as! ThirdTableViewCell
cell.pastaImageView.image = UIImage(named: "pasta")
return cell
}
使用indexPath.row % 3 == 0
進行模數運算,因此僅當indexPath.row / 3等於整數時,它才為您提供“ FirstCell”。 else if
沒有測試,那么您將擁有另一個,因此將為所有其他行調用它。 最終,您的else
永遠不會被呼叫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.