我正试图从一个nib文件创建自定义的表格视图单元格。我参考了这篇文章(链接)。我遇到了两个问题。
我创建了一个.xib文件,并将UITableViewCell对象拖到上面。我创建了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
}
}
这段代码没有任何错误,但是当我在模拟器中运行它时,它看起来是这样的。
在Storyboard中的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项目在这里演示问题。