iOS TableView reload and scroll top

后端 未结 6 546
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 07:50

the second day I can not solve the problem with the table.

We have a segmentedControl which, when changed, changes the table. Suppose that there are 3 elements in th

6条回答
  •  半阙折子戏
    2020-12-03 08:06

    UItableView method scrollToRow(at:at:animated:) Scrolls through the table view until a row identified by index path is at a particular location on the screen.

    Use

    tableView.scroll(to: .top, animated: true)
    

    You can use my extension

    extension UITableView {
    
        public func reloadData(_ completion: @escaping ()->()) {
            UIView.animate(withDuration: 0, animations: {
                self.reloadData()
            }, completion:{ _ in
                completion()
            })
        }
    
        func scroll(to: scrollsTo, animated: Bool) {
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
                let numberOfSections = self.numberOfSections
                let numberOfRows = self.numberOfRows(inSection: numberOfSections-1)
                switch to{
                case .top:
                    if numberOfRows > 0 {
                         let indexPath = IndexPath(row: 0, section: 0)
                         self.scrollToRow(at: indexPath, at: .top, animated: animated)
                    }
                    break
                case .bottom:
                    if numberOfRows > 0 {
                        let indexPath = IndexPath(row: numberOfRows-1, section: (numberOfSections-1))
                        self.scrollToRow(at: indexPath, at: .bottom, animated: animated)
                    }
                    break
                }
            }
        }
    
        enum scrollsTo {
            case top,bottom
        }
    }
    

提交回复
热议问题