我目前正在以编程方式学习Swift
。我想将tableView
添加到viewController
(为了能够稍后操作约束)并使用TableViewCell
自定义单元格。TableView中的空单元格与自定义TableViewCell - Swift
当我使用storyboard
时,我可以闭上眼睛,但是当我试图用直接代码来做到这一点时,我有空单元。
我的故事板是由一(1)具有自定义类的ViewController
我已经看过其他类似的问题,但解决方案的非工作过空viewController
。想知道我忽略了什么(可能是简单的事情)。先谢谢您的帮助!
ViewController.swift:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var tableView: UITableView = UITableView()
var items: [String] = ["Viper", "X", "Games"]
override func viewDidLoad() {
tableView.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat
{
return 50
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
//cell.textLabel?.text = self.items[indexPath.row]
cell.companyName.text = "name"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
TableViewCell:
import UIKit
class TableViewCell: UITableViewCell {
var companyName = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
companyName.frame = CGRectMake(0, 0, 200, 20)
companyName.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(companyName)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
谢谢!这是我在被@replman指向正确方向之后得到的结果。 “使用前初始化您的标签”意味着什么。它已初始化。 – Geppelt
你只是设置了UILabel的框架,因为在你添加到任何视图之前,你还没有为你的单元格创建xib,所以最好这样做,所以你最终不会得到零对象。还应该在cell类中实现prepareForReuse方法,以便在下次使用该对象之前进行清理。 –
我不想要一个xib文件,我不明白你的意思; UIImageView被声明,构建并添加。我不是经验和问题的零对象。 – Geppelt