0

Мне нужно сделать примерно такое отображение в tableView

x
  x
   x
    x
   x
  x
x

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

попытался такое сделать :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeTableViewCell
    let firstVisible = tableView.indexPathsForVisibleRows?.first?.row
    let lastVisible = tableView.indexPathsForVisibleRows?.last?.row

    let isfirst = ( indexPath.row >= firstVisible! && indexPath.row <= (lastVisible! / 2)) 
    var margin = (isfirst) ? 10 : 10 * (tableView.visibleCells.count / 2)
    let ind = (isfirst) ? indexPath.row - firstVisible! : lastVisible! - indexPath.row
    if ind > firstVisible! {
        for _ in firstVisible!..<ind {
            margin = margin + 10
        }
    }

    cell.subviews.forEach { (sub) in
        sub.removeFromSuperview()
    }
    let btn = UIButton()
    btn.setTitle("test \(indexPath.row)", for: .normal)
    btn.frame = CGRect(x: margin, y: 5, width: 100, height: 100)
    cell.addSubview(btn)
    return cell
}

отображается, как я хочу, но до первой прокрутки тк в последствии сбивается (оно и понятно, тк метод вызывается лишь раз для ячейки при ее появлении в поле видимости, а не каждый раз при прокрутке)

Можно ли как-то сделать такую прокрутку ? буду рад любым советам

2
  • Попробуйте использовать для этой цели методscrollViewDidScroll:
    – schmidt9
    6 мар 2020 в 4:03
  • @schmidt9 попытался взывать reloadRows в этом методе, но все залогало (( а есть ли метод, который обновляет все видимые ячейки при скролле ?
    – alex king
    6 мар 2020 в 7:37

1 ответ 1

0

Набросал вот такое решение

Ячейка для таблицы - смещение сделано с помощью анимированного изменения левого отступа

class TableViewCell: UITableViewCell {

    @IBOutlet var movableButton: UIButton!
    @IBOutlet private var buttonLeadingConstraint: NSLayoutConstraint!

    var buttonLeftMargin: CGFloat {
        get {
            if (buttonLeadingConstraint != nil) {
                return buttonLeadingConstraint.constant
            }

            return 0
        }

        set {
            if (buttonLeadingConstraint != nil) {
                animateLeftMargin(to: newValue)
            }
        }
    }

    private (set) var initialButtonLeftMargin: CGFloat = 0

    override func awakeFromNib() {
        initialButtonLeftMargin = buttonLeadingConstraint.constant
    }

    func animateLeftMargin(to newValue: CGFloat) {
        UIView.animate(withDuration: 0.1) {
            self.buttonLeadingConstraint.constant = newValue
            self.layoutIfNeeded()
        }
    }

}

А вот класс-наследник UITableViewController, в таблице которого эти ячейки используются. Мы сохраняем начальные отступы ячеек для ограничения анимации и добавляем отступы через scrollViewDidScroll(:)

class MyTableViewController: UITableViewController {

    var data: [String] = []
    var initialCellsLeftMargin: CGFloat = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")

        for i in 0..<100 {
            data.append("item \(i)")
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        // обновляем здесь принудительно, так как scrollViewDidScroll
        // не обязательно вызывается на старте
        updateMargins()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Attempted to access the table view's visibleCells while they were in the process of being updated, which is not allowed. Make a symbolic breakpoint at UITableViewAlertForVisibleCellsAccessDuringUpdate to catch this in the debugger and see what caused this to occur. Perhaps you are trying to ask the table view for the visible cells from inside a table view callback about a specific row?
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        cell.movableButton.setTitle(data[indexPath.row], for: .normal)

        if initialCellsLeftMargin == 0 {
            initialCellsLeftMargin = cell.initialButtonLeftMargin
        }

        return cell
    }

    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        updateMargins()
    }

    func updateMargins() {
        guard
            let visibleIndexPaths = tableView.indexPathsForVisibleRows,
            let firstIndexPath = visibleIndexPaths.first else {
            return
        }

        var margin = initialCellsLeftMargin
        let marginStep: CGFloat = 10.0

        visibleIndexPaths.forEach { indexPath in
            let cell = tableView.cellForRow(at: indexPath) as! TableViewCell

            let firstVisibleRow = firstIndexPath.row
            let middleVisibleRow = firstVisibleRow + visibleIndexPaths.count / 2
            let isFirstHalf = (indexPath.row >= firstVisibleRow && indexPath.row < middleVisibleRow)

            margin += (marginStep * (isFirstHalf ? 1 : -1));

            if margin < cell.initialButtonLeftMargin {
                margin = cell.initialButtonLeftMargin
            }

            cell.buttonLeftMargin = margin
        }
    }

} 

Результат

введите сюда описание изображения

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.