我正在try 从nib创建一个自定义表视图单元格.我指的是第here条.我面临两个问题.
我创建了一个.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
}
}
这段代码没有任何错误,但是当我在模拟器中运行它时,它看起来是这样的.
在情节提要中的UITableViewController中,我没有对单元格做任何操作.标识符为空,没有子类.我try 向原型单元添加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的子类.但是我得到以下错误,
Overriding method with selector 'tableView:willDisplayCell:forRowAtIndexPath:' has incompatible type '(UITableView!, CustomOneCell!, NSIndexPath!) -> ()'
有人知道如何解决这些错误吗?这些在Objective-C中似乎很有效.
谢谢.
编辑:我刚刚注意到如果我把模拟器的方向改成横向,再把它调回纵向,单元格就会出现!我还是弄不明白发生了什么事.如果您有时间快速浏览一下,我上传了一个Xcode项目here,演示了这个问题.