【发布时间】:2019-05-09 00:05:09
【问题描述】:
我有 2 个 xib 文件:自定义 UIView 和自定义单元 xib。 我还有一个只包含 UILabel 的自定义单元类。 名字都是正确的。
UITableView 的代理连接到视图。
我需要将 UITableView 添加到 UIView。从我读过的教程中,这是如何添加它的。但是由于某种原因,这不起作用,我得到了 2 种类型的错误代码,说我需要注册单元笔尖,或者在展开可选时它发现 nil。我究竟做错了什么?请帮忙!
private let myArray: NSArray = ["First","Second","Third"]
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myArray[indexPath.row])")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
cell.textLabel!.text = "\(myArray[indexPath.row])"
return cell
}
@IBOutlet var contentView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var HelperLabel: UILabel!
override init(frame: CGRect){
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit(){
let nib = UINib(nibName: "MyCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "MyCell")
tableView.dataSource = self
tableView.delegate = self
self.addSubview(tableView)
【问题讨论】:
-
您是否为创建的单元格创建了自定义类?
-
是的。我通过故事板将它连接到自定义 Xib。
标签: ios uitableview uiview uiviewcontroller swift4