简体   繁体   中英

How to increase index within a loop & stop enumerating?

I've ran into a situation where I need a loop, but the code below returns only the very last index value. I need it to return the next value and stop enumerating. To explain better, say I have numbers 0-10, when pressing a button I need the index to increase by one. Now say I keep pressing this button until the index reaches 10, on the next press, the index needs to be back at zero (aka cycle through.)

Any help would be appreciated & I will most definitely accept the best answer.

Thanks in advance!

//grabs current index in a scrollview
long long currentSelectedIndex = [preview.swipeView currentIndex];
long long totalNumberOfAvailableSlots = [preview.swipeView indexTotal]; //index total is never an absolute value

@autoreleasepool {
    //currentSelectedIndex is supposed/always to be zero on first run
    for (int i; = (int)currentSelectedIndex; i <= totalNumberOfAvailableSlots; i++){
        NSLog(@"loop: %d", i);
        if (i == totalNumberOfAvailableSlots){
            i = -1;
            [preview.swipeView scrollToIndex:i]; //this will cause [preview.swipeView currentIndex] to be updated with "i" value.
        }
    }
}

As per my comment, the behaviour you seem to be after is to automatically swipe through the contents of swipeView.

Make a timer which calls the swipeToNext method:

myTimer = [NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(swipeToNext) userInfo:nil repeats:YES];

Then handle the swipe:

- (void)swipeToNext { if ([preview.swipeView currentIndex] < [preview.swipeView indexTotal]) { //Can swipe forward [preview.swipeView scrollToIndex:[preview.swipeView currentIndex]+1]; } else { //At last index. Need to go to first. [preview.swipeView scrollToIndex:0]; } }

sounds like you need currentSelectedIndex to go through this repeating sequence 0, 1, 2, 3, 4,5, 6, 7, 8, 9, 10, 0, 1, ...

within formLoad you need to initialise your counter

 currentSelectedIndex = 0

within the button pressed method, increment the counter - but using the modulo operator to return the remainder - in this case of dividing by 11

currentSelectedIndex = (currentSelectedIndex + 1) % 11

in general, you can make a sequence of 0...n like this

currentSelectedIndex = (currentSelectedIndex + 1) % (n + 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM