好吧,我已经创建了一个名为UITableViewCell
的{{1}}子类,而我想要的只是一个包含两个TwoColumnCell
的单元格。
这是我的子类:
UILabels
这是我的控制器:
import UIKit
class TwoColumnCell: UITableViewCell
{
var firstNameLabel:UILabel = UILabel()
var lastNameLabel:UILabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(firstNameLabel)
self.contentView.addSubview(lastNameLabel)
}
override func layoutSubviews()
{
super.layoutSubviews()
firstNameLabel = UILabel(frame: CGRectMake(20.0, 10, self.bounds.size.width/2, self.bounds.size.height))
lastNameLabel = UILabel(frame: CGRectMake(self.bounds.size.width/2 + 5, 10, self.bounds.size.width/2, self.bounds.size.height))
}
override init() { super.init(); }
required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override init(frame: CGRect) { super.init(frame: frame) }
}
但是当我运行应用程序时,表视图为空。它可能是一个import UIKit
class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.registerClass(TwoColumnCell.self, forCellReuseIdentifier: "TwoColumnCell")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 2;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cellIdendifier: String = "TwoColumnCell"
var cell:TwoColumnCell = tableView.dequeueReusableCellWithIdentifier(cellIdendifier, forIndexPath: indexPath) as! TwoColumnCell
cell.firstNameLabel.text = "Jony"
cell.lastNameLabel.text = "Ive"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
问题,但我似乎无法弄明白。有什么想法吗?
答案 0 :(得分:0)
您的layoutSubviews
正在创建新 UILabels而不是更新现有的框架。只需要一些调整:
override func layoutSubviews()
{
super.layoutSubviews()
firstNameLabel.frame = CGRectMake(20.0, 10, self.bounds.size.width/2, self.bounds.size.height)
lastNameLabel.frame = CGRectMake(self.bounds.size.width/2 + 5, 10, self.bounds.size.width/2, self.bounds.size.height)
}