Xcode Playground中UITableView无法显示文本/副标题求助
解决Live View中Subtitle样式表格单元格不显示的问题
嘿,我看到你的问题啦!问题出在你还没实现UITableView的核心数据源方法——你的WWDCMasterViewController虽然继承了UITableViewController,但既没告诉表格要显示多少行,也没配置每行的单元格样式与内容,再加上缺少Live View的启动代码,自然看不到subtitle样式的单元格啦。
修正后的完整代码
import PlaygroundSupport import UIKit class WWDCMasterViewController: UITableViewController { var reasons = ["WWDC is great", "the people are awesome", "I love lab works", "key of success"] override func viewDidLoad() { super.viewDidLoad() // 别忘了调用父类的viewDidLoad! title = "Reasons I should..." } // MARK: - UITableView Data Source Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 返回数组元素数量,告诉表格有多少行 return reasons.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 复用单元格,指定样式为.subtitle(自带主副标题两个标签) let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil) // 设置主标题内容 cell.textLabel?.text = reasons[indexPath.row] // 设置副标题内容,这里可以换成你需要的文本 cell.detailTextLabel?.text = "WWDC 2017专属理由" return cell } } // 把ViewController实例赋值给Live View,让Playground显示界面 PlaygroundPage.current.liveView = WWDCMasterViewController(style: .plain)
关键修复点说明
- 调用父类
viewDidLoad:你之前的代码没写super.viewDidLoad(),这会导致UITableViewController的基础初始化逻辑不执行,可能引发表格异常。 - 实现数据源方法:
tableView(_:numberOfRowsInSection:):返回数据源数组的长度,确定表格行数。tableView(_:cellForRowAt:):创建/复用.subtitle样式的单元格,并分别给textLabel(主标题)和detailTextLabel(副标题)赋值。
- 启动Live View:最后一行代码把ViewController实例绑定到Playground的Live View,这是让界面显示出来的必要步骤。
内容的提问来源于stack exchange,提问作者singlepiece000
相关产品推荐
相关产品推荐

