【问题标题】:How to programmatically scroll to cell in UICollectionView?如何以编程方式滚动到 UICollectionView 中的单元格?
【发布时间】:2021-09-02 12:00:44
【问题描述】:

我有一个带有图像的 UICollectionView。当我在 SideMenu 中选择一个项目时,我实现了一个包含 TableView 的 SideMenu 我希望它自动滚动到 CollectionView 中的特定行

我在didSelectRowAt做什么?

下面是我完整的 ViewController 类

import SideMenu
import UIKit

class ViewController: UIViewController {
    var menu: SideMenuNavigationController?
    
    @IBOutlet weak var collectionView: UICollectionView!
    var imgArr = ["1","2","3","4","5","6","7","8","9","10"]
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        menu = SideMenuNavigationController(rootViewController: MenuListController())
        menu?.leftSide = true
        SideMenuManager.default.leftMenuNavigationController = menu
        SideMenuManager.default.addPanGestureToPresent(toView: self.view)
    }
    
    @IBAction func didTapMenu(){
        present(menu!, animated: true)
    }

}


extension ViewController : UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? DataCollectionViewCell
        cell?.img.image = UIImage(named:imgArr[indexPath.row])
        return cell!
    }
    
}

class MenuListController:UITableViewController{
    
    var items = ["First", "Second"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UITableView.self, forCellReuseIdentifier: "cellmenu")
        
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellmenu", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
      override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("selected " + items[indexPath.row])
        // WHAT DO I DO HERE????
       
       
        
    }
    
}

【问题讨论】:

标签: ios swift uitableview uicollectionview


【解决方案1】:

在 IndexPath 中,给出目标单元格的行和节。

collectioView.scrollToItem(at: IndexPath(row: 0, section: 0), at: .top, animated: true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    相关资源
    最近更新 更多