【发布时间】:2014-10-21 21:38:36
【问题描述】:
我正在尝试从笔尖创建自定义表格视图单元格。我指的是这篇文章here。我面临两个问题。
我创建了一个带有 UITableViewCell 对象的 .xib 文件。我创建了UITableViewCell 的子类并将其设置为单元格的类,并将 Cell 设置为可重用标识符。
import UIKit
class CustomOneCell: UITableViewCell {
@IBOutlet weak var middleLabel: UILabel!
@IBOutlet weak var leftLabel: UILabel!
@IBOutlet weak var rightLabel: UILabel!
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
在 UITableViewController 我有这段代码,
import UIKit
class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
var items = ["Item 1", "Item2", "Item3", "Item4"]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - UITableViewDataSource
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let identifier = "Cell"
var cell: CustomOneCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomOneCell
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomCellOne", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomOneCell
}
return cell
}
}
这段代码没有错误,但是当我在模拟器中运行它时,它看起来像这样。
在情节提要的 UITableViewController 中,我没有对单元格做任何事情。空白标识符,没有子类。我尝试将 Cell 标识符添加到原型单元格并再次运行它,但我得到了相同的结果。
我遇到的另一个错误是,当我尝试在 UITableViewController 中实现以下方法时。
override func tableView(tableView: UITableView!, willDisplayCell cell: CustomOneCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
cell.middleLabel.text = items[indexPath.row]
cell.leftLabel.text = items[indexPath.row]
cell.rightLabel.text = items[indexPath.row]
}
正如我提到的文章中所示,我将cell 参数的类型形式UITableViewCell 更改为CustomOneCell,这是我的UITableViewCell 的子类。但我收到以下错误,
使用选择器 'tableView:willDisplayCell:forRowAtIndexPath:' 的覆盖方法具有不兼容的类型 '(UITableView!, CustomOneCell!, NSIndexPath!) -> ()'
有人知道如何解决这些错误吗?这些似乎在 Objective-C 中运行良好。
谢谢。
编辑:我刚刚注意到,如果我将模拟器的方向更改为横向并将其转回纵向,则会出现单元格!我仍然无法弄清楚发生了什么。我上传了一个 Xcode 项目 here 演示了这个问题,如果你有时间快速浏览一下。
【问题讨论】:
标签: ios uitableview swift ios8