Search code examples
iosobjective-cuiscrollviewuicollectionviewnstimer

Cannot make a slide image in objective-c of Xcode by UICollectionView and NSTimer


Hi I have a problem with NSTimer when I pass an param to scrollToItemAtIndexPath that it has alway be terminated. Have anyone can help?

SlideCollectionViewCell *cell = [collectionImageSlideView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

cell.showImage.image = [UIImage imageNamed:[images objectAtIndex:indexPath.row]];
NSInteger rowIndex = indexPath.row;
NSInteger imageCount = self->images.count-1;
if(rowIndex<imageCount){
    rowIndex = rowIndex+1;

}else{
    rowIndex = 0;
}
scrollingTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0
                target: self
                selector:@selector(startTimer:)
                userInfo: @(rowIndex) repeats:YES];
return cell;

enter image description here


Solution

  • This is because you're passing an NSInteger in an NSIndexpath variable you need to make an NSIndexpath then pass it to the functions like : -

    cell.showImage.image = [UIImage imageNamed:[images objectAtIndex:indexPath.row]];
    NSInteger rowIndex = indexPath.row;
    NSInteger imageCount = self->images.count-1;
    if(rowIndex<imageCount){
        rowIndex = rowIndex+1;
    
    }else{
        rowIndex = 0;
    }
    NSIndexPath *indexToPass=[NSIndexPath indexPathForRow:rowIndex inSection:indexPath.section];
    scrollingTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0
                target: self
                selector:@selector(startTimer:)
                userInfo:indexToPass repeats:YES];
    return cell;