Как правильно настроить пользовательскую ячейку UITableView - PullRequest
0 голосов
/ 27 сентября 2018

Я пытаюсь создать пользовательскую ячейку для своего UITableView, но использую ли я ячейку с идентификатором из раскадровки или полностью создаю свою собственную ячейку, по какой-то причине данные загружаются, но при прокрутке это всего 1 ячейка.Он показывает только 1 ячейку по одной за раз.Вот как я сейчас пытаюсь это сделать:

 let cell = UITableViewCell()
let cellTextLabel = UILabel()
let cellDetailLabel = UILabel()
let imageView = UIImageView()
let phImage = UIImage(named: "CryptiXJustX")

 func configureCustomCell() {
    cell.addSubview(imageView)
    imageView.backgroundColor = .clear
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
    imageView.leftAnchor.constraint(equalTo: cell.leftAnchor, constant: 10).isActive = true
    imageView.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
    cell.addSubview(cellTextLabel)
    cellTextLabel.translatesAutoresizingMaskIntoConstraints = false
    cellTextLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
    cellTextLabel.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -10).isActive = true
    cellTextLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 10).isActive = true
    cellTextLabel.textColor = .white
    cell.addSubview(cellDetailLabel)
    cellDetailLabel.translatesAutoresizingMaskIntoConstraints = false
    cellDetailLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
    cellDetailLabel.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -10).isActive = true
    cellDetailLabel.topAnchor.constraint(equalTo: cellTextLabel.bottomAnchor, constant: 10).isActive = true
    cellDetailLabel.textColor = .white
    cellDetailLabel.font = cellDetailLabel.font.withSize(12)
    cellDetailLabel.numberOfLines = 3

    cell.backgroundColor = .clear
    cell.textLabel?.textColor = .white
    cell.detailTextLabel?.textColor = .white

    imageView.image = phImage
}

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

     var index = indexPath.row
    if contentData.count > 0 {
    cellTextLabel.text = contentData[index].title
    cellDetailLabel.text = contentData[index].text
        return cell
    } else {
        return cell
    }
}

I configureCustomCell() in ViewDidLoad(), я чувствую, что это как-то связано с методом cellforRowAt, но я не уверен.

override func viewDidLoad() {
    super.viewDidLoad()

     view.backgroundColor = .clear

    configureCustomCell()

    NewsAPI.shared.getData(arr: true) { (success) in
        DispatchQueue.main.async {

            self.contentData = NewsAPI.shared.contentData[0].posts
            self.tableView.reloadData()
        }
    }
    }

Спасибо.

Ответы [ 2 ]

0 голосов
/ 27 сентября 2018

Создайте пользовательский UITableViewCell, как показано ниже

class CustomCell: UITableViewCell {
}

И в контроллере viewDidLoad вы зарегистрируете вышеуказанную ячейку, как показано ниже

tableView.registerClass(CustomCell.self, forCellReuseIdentifier: "CustomCell")
0 голосов
/ 27 сентября 2018

Причина в том, что вы используете одну ячейку экземпляра для всего представления таблицы.Это неправильный способ загрузки ваших данных в ваш UITableView

Но вы можете попробовать использовать вместо:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var index = indexPath.row
    if contentData.count > 0 {
        cellTextLabel.text = contentData[index].title
        cellDetailLabel.text = contentData[index].text

        return cell
    } else {
        return cell
    }
}

Попробуйте использовать так:

class MyCell: UITableViewCell {
    let cellTextLabel = UILabel()
    let cellDetailLabel = UILabel()
    let imageView = UIImageView()
    let phImage = UIImage(named: "CryptiXJustX")

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.addSubview(imageView)
        imageView.backgroundColor = .clear
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
        imageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
        imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10).isActive = true
        imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
        contentView.addSubview(cellTextLabel)
        cellTextLabel.translatesAutoresizingMaskIntoConstraints = false
        cellTextLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
        cellTextLabel.rightAnchor.constraint(equalTo: contentView.contentView.rightAnchor, constant: -10).isActive = true
        cellTextLabel.topAnchor.constraint(equalTo: contentView.contentView.topAnchor, constant: 10).isActive = true
        cellTextLabel.textColor = .white
        contentView.addSubview(cellDetailLabel)
        cellDetailLabel.translatesAutoresizingMaskIntoConstraints = false
        cellDetailLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
        cellDetailLabel.rightAnchor.constraint(equalTo: contentView.contentView.rightAnchor, constant: -10).isActive = true
        cellDetailLabel.topAnchor.constraint(equalTo: cellTextLabel.bottomAnchor, constant: 10).isActive = true
        cellDetailLabel.textColor = .white
        cellDetailLabel.font = cellDetailLabel.font.withSize(12)
        cellDetailLabel.numberOfLines = 3

        contentView.backgroundColor = .clear
        contentView.textLabel?.textColor = .white
        contentView.detailTextLabel?.textColor = .white
    }
}

На вас ViewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    // if you are not using storyboard, make sure you are registered the cell ID
    self.tableView!.register("CellID", forCellReuseIdentifier: tableReuseIdentifier)
}

Наконец:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: 'CellID', for: indexPath) as! MyCell

    cell.imageView.image = phImage
    cell.cellTextLabel.text = contentData[indexPath.row].title
    cell.cellDetailLabel.text = contentData[indexPath.row].text

    return cell
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...