Пользовательские ячейки TableViewCell не отображаются - PullRequest
0 голосов
/ 22 февраля 2019

Так что я довольно новичок в разработке под iOS.Я пытаюсь создать все программно, поэтому моя раскадровка пуста.В настоящее время я пытаюсь получить TableView с пользовательскими ячейками.TableView работает и выглядит нормально, когда я использую стандартный UITableViewCell.Я создал очень простой класс под названием «GameCell».По сути, я хочу создать здесь ячейку с несколькими метками и, возможно, некоторыми дополнительными объектами UIO в будущем (imageView и т. Д.).По какой-то причине пользовательские ячейки не отображаются.

Класс игровой ячейки:

class GameCell: UITableViewCell {

    var mainTextLabel = UILabel()
    var sideTextLabel = UILabel()

    func setLabel() {
        self.mainTextLabel.text = "FirstLabel"
        self.sideTextLabel.text = "SecondLabel"
    }
}

Здесь приведен дополнительный необходимый код для получения количества строк и возврата ячеек в TableView, который есть в моем ViewController.self.lastGamesCount здесь только Int и определенно не ноль, когда я его печатаю.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.lastGamesCount
        }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! GameCell

В моем viewDidLoad () я регистрирую ячейки следующим образом:

tableView.register(GameCell.self, forCellReuseIdentifier: cellID)

Когда я запускаювсе, что сборка прошла успешно, я вижу панель навигации моего приложения, и все, кроме TableView пусто.Я возвращаюсь к обычному UITableViewCell, и ячейки снова появляются.Что мне здесь не хватает?Любая помощь приветствуется.

Спасибо!

1 Ответ

0 голосов
/ 22 февраля 2019

Проблема в том, что вам нужно установить ограничения для этих меток

var mainTextLabel = UILabel()
var sideTextLabel = UILabel()

после добавления их в ячейку

class GameCell: UITableViewCell {

    let mainTextLabel = UILabel()
    let sideTextLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setLabel()
    }
    func setLabel() { 
        self.mainTextLabel.translatesAutoresizingMaskIntoConstraints = false
        self.sideTextLabel.translatesAutoresizingMaskIntoConstraints = false 
        self.contentView.addSubview(mainTextLabel)
        self.contentView.addSubview(sideTextLabel) 
        NSLayoutConstraint.activate([  
            mainTextLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), 
            mainTextLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor), 
            mainTextLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor,constant:20), 
            sideTextLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), 
            sideTextLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor), 
            sideTextLabel.topAnchor.constraint(equalTo: self.mainTextLabel.bottomAnchor,constant:20), 
            sideTextLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor,constant:-20)
        ])
        self.mainTextLabel.text = "FirstLabel"
        self.sideTextLabel.text = "SecondLabel"
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    } 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...