【发布时间】:2017-08-02 10:00:15
【问题描述】:
我正在测试如何为 UITableView 中的不同部分使用不同的单元格类型。我为此创建了一个项目。故事板如下所示:
如您所见,我插入了两个外观略有不同的原型单元。这是我的视图控制器:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var firstSection = "first title"
var secondSection = ["second title", "third title"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
return secondSection.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "first_cell", for: indexPath) as! FirstCell
cell.title.text = self.firstSection
return cell
}
else {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "second_cell", for: indexPath) as! OtherCell
cell.title.text = self.secondSection[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Section 1"
}
else {
return "Section 2"
}
}
}
以及我的两种表格视图单元格的定义:
class FirstCell: UITableViewCell {
@IBOutlet var title: UILabel!
}
class OtherCell: UITableViewCell {
@IBOutlet var title: UILabel!
}
我确保在故事板中指定原型单元的类名,并设置它们的重用标识符。但是,编译后的应用程序显示了这种意外行为:
首先,不显示任何单元格。其次,在第二部分标题下,有一个灰色区域,带有一些我不知道其来源的 x 插图。我该如何解决这个问题?提前致谢。
【问题讨论】:
-
你可能想实现
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat -
@Larme 成功了!非常感谢。
标签: ios uitableview swift3