使用Swift和Storyboard在动态TableViewCells中创建UILabels



所以我试图在动态TableView中创建UILabels,并设置一个子类UITableViewCell,但当我构建项目时,UILabels不显示任何文本。

GamesFeedCell

import UIKit
class GamesFeedCell: UITableViewCell {
    @IBOutlet weak var game1Name: UILabel!
    @IBOutlet weak var game2Name: UILabel!
    @IBOutlet weak var score1: UILabel!
    @IBOutlet weak var score2: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization codea
    }
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }
}

GamesFeedViewController

import UIKit
class GamesFeedViewController: UIViewController, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerNib(UINib(nibName: "GamesFeedCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "gamesFeedCell")
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @available(iOS 2.0, *)
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 8
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: GamesFeedCell! = tableView.dequeueReusableCellWithIdentifier("gamesFeedCell") as! GamesFeedCell
        if (cell == nil) {
            cell = GamesFeedCell()
        }
        (cell as GamesFeedCell).game1Name.text = "game1"
        (cell as GamesFeedCell).game2Name.text = "game2"
        (cell as GamesFeedCell).score1.text = "score1"
        (cell as GamesFeedCell).score2.text = "score2"
        return cell!
    }
}

我会验证两件事:

  1. dequeueReusableCellWithIdentifier实际上返回了GamesFeedCell的一个实例,如果不是,请确保标识符与单元的接口生成器中的标识符匹配
  2. UILabel的IBOutlets已连接

我也不认为这个代码是必要的,并且可能会导致错误,因为如果cell恰好是nil,那么它通常是init'd,因此您在接口生成器的动态原型中设置的任何内容都不会出现。我的建议是:删除这段代码(这可能会暴露出一个错误,即dequeueReusableCellWithIdentifier实际上并没有退出任何队列,因为标识符是错误的。

if (cell == nil) {
    cell = GamesFeedCell()
}

最新更新