UICollectionView scrollToItem() 不起作用

来源:互联网 发布:淘宝达人账号怎么取消 编辑:程序博客网 时间:2024/06/05 20:49

今天在做东西的时候又遇到这样一个问题,把 UICollectionView 嵌套在 UIViewController 中使用,在想用 scrollToItem() 方法时,怎么都不起作用,找了半天,原来是 位置属性设置错了。

原本的代码是

// viewDidLoad 里面navigationItem.rightBarButtonItem = UIBarButtonItem(title: "定位", style: .plain, target: self, action: #selector(locatSelectedCell))// 外部方法func locatSelectedCell () {        if let lastSelectedIndex = lastSelectionID {            DispatchQueue.main.async {                self.thingsCollectionView.scrollToItem(at: IndexPath(item: lastSelectedIndex, section: 0), at: .centeredHorizontally, animated: true)            }        }    }

错误就出在 at: .centeredHorizontally ,因为我的 collectinoView 的方向是纵向的,所以应该是 at: .centeredVertically 纵向居中显示对应的 cell

    func locatSelectedCell () {        if let lastSelectedIndex = lastSelectionID {            DispatchQueue.main.async {                self.thingsCollectionView.scrollToItem(at: IndexPath(item: lastSelectedIndex, section: 0), at: .centeredVertically, animated: true)            }        }    }