Переопределение поля между UITableView и пользовательской ячейкой - PullRequest
0 голосов
/ 04 июля 2019

У меня есть UITableView, созданный в коде как таковой:

 lazy var tableView:UITableView = {
    let tv = UITableView()
    tv.delegate = self
    tv.dataSource = self
    tv.remembersLastFocusedIndexPath = false
    tv.translatesAutoresizingMaskIntoConstraints = false
    return tv
}

Я ограничиваю его родительским представлением:

private func setup() {
    tableView.register(LiveTVCell.self, forCellReuseIdentifier: "cell")
    self.view.addSubview(tableView)
    tableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
    tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
    tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true
    tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
}

В ячейке Cusom нет ничего, кроме красного фона. После визуализации ячейка показывает 90 точек с левой стороны экрана, где начинается просмотр таблицы. Я пытался использовать layoutMargins, а также contentInset безрезультатно. Если я сделаю что-то вроде: print(self.tableView.layoutMargins), это показывает, что левое поле действительно 90.

Единственный способ преодолеть это поведение - добавить следующее: tv.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: -180, bottom: 0, trailing: -90) Мне не нравится это решение, так как оно опирается на магические числа.

Нет, как я могу удалить эти 90 пунктов левого поля без вышеуказанного исправления взлома?

Запрошено больше кода, поэтому я включаю функции делегата табличного представления и источник данных ниже:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.liveArray.first?.shows.count ?? 0
    }

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

    if !self.fetchedRows.contains(indexPath.row) {
        self.fetchedRows.append(indexPath.row)
        self.spinner.start()
        MediaFeedController.retrieveShows(showIDs: liveArray.first!.shows,forSection:indexPath.row) { [unowned self](row) in
            self.spinner.stop()
            guard row != nil else {return}
            UIView.performWithoutAnimation {
                self.tableView.reloadRows(at: [IndexPath(row: row!, section: 0)], with: .none)
            }
        }
    }

    cell.showID = liveArray.first!.shows[indexPath.row]
    //print(self.tableView.layoutMargins)

    return cell
}

func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool {
    return false
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 70
}

Вот ячейка просмотра таблицы. Имейте в виду, что проблема возникает, если я удаляю все это из ячеек таблицы и просто устанавливаю цвет фона:

import UIKit

class LiveTVCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

var showID:Int! {
    didSet {
        setup()
    }
}

private var collectionView: UICollectionView!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

override func layoutSubviews() {
    super.layoutSubviews()
}

func setup() {


    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal

    collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor(named: "collectionView")
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.remembersLastFocusedIndexPath = true
    collectionView.register(ChannelCVCell.self, forCellWithReuseIdentifier: "channelCell")
    collectionView.register(ProgramCVCell.self, forCellWithReuseIdentifier: "programCell")

    self.addSubview(collectionView)
    collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
    collectionView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}

// MARK: - Collectionview Delegate & Datasource

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if indexPath.section == 0 {
        let channelCell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelCell", for: indexPath) as! ChannelCVCell
        channelCell.showID = showID
        return channelCell
    } else {
        let programCell = collectionView.dequeueReusableCell(withReuseIdentifier: "programCell", for: indexPath) as! ProgramCVCell
        programCell.showID = showID
        return programCell
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if indexPath.section == 0 {
        return CGSize(width: 177, height: 70)
    } else {
        return CGSize(width: collectionView.frame.size.width, height: 70)
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    if section == 0 {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    } else {
        return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
    }
}

// MARK: - CollectionView Focus Delegates

func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    //guard let index = context.nextFocusedIndexPath?.row else {return}
}

override func prepareForReuse() {
    self.collectionView.removeFromSuperview()
}

}

Обновление:

Вы можете полностью удалить пользовательскую ячейку и ничего не иметь в cellForRowAt и вернуть универсальный UITableViewCell, а поле макета таблицы слева равно 90. Фактически, вторую вы добавляете таблицу в подпредставление и привязываете ее, сейчас 90.

...