Для вашего массива длина массива равна 3 (например, name.length = 3). Но поскольку он хранит элемент, начинающийся с индекса 0, он имеет максимальный индекс 2.
Итак, вместо 'i ** & lt; = name.length' вы должны написать 'i & lt; ** name.length' чтобы избежать «ArrayIndexOutOfBoundsException».
Я действительно не знаю, будет ли это работать очень долго и слишком сложно, но я не могу думать ни о чем другом.
ViewController
var scrollArray = [Int]()
var runbefore = false
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let post = posts[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CellClass
cell.button.tag = indexPath.item
cell.button.addTarget(self, action: #selector(didLike(sender:)), for: .touchUpInside)
cell.viewpassed = self
cell.indexofCell = indexPath.row
if scrollArray[indexPath.row] != nil {
cell.movetoNumber = scrollArray[indexPath.row]
}
if runbefore == false {
scrollArray.append(0)
if indexPath.row = posts.count - 1 {
runbefore = true
}
}
}
Класс ячейки
extension NoticeLetterViewCell: UIScrollViewDelegate {
var movetoNumber = 0
var indexofCell = 0
public weak var viewpassed : ViewController? //This is what class you have the cell for item at function
override func awakeFromNib() {
if movetoNumber != 0 {
//Move the scrollView to movetoNumberPoint Run whatever action your Want HERE
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = Int(floor(scrollView.contentOffset.x / UIScreen.main.bounds.width))
if page != 0 {
viewpassed.scrollArray.remove(at: indexofCell)
viewpassed.scrollArray.insert(page, at: indexofCell)
}
}
}