我知道很多次都会问这个问题,但我没有找到解决问题的方法。我在ViewDidLoad上声明counter是0,
- (void)viewDidLoad
{
[super viewDidLoad];
counter = 0;
[stgImage1 setImage:[UIImage imageNamed:[imageStr objectAtIndex:counter]]];
}
这是我的下一个和上一个操作,
-(void)btnClicked:(UIButton*)btn{
if (btn.tag==1) {
if (counter < [textStr count]-1) {
counter++;
NSLog(@"%i", counter);
[stgImage1 setImage:[UIImage imageNamed:[imageStr objectAtIndex:counter]]];
}
if(counter > [textStr count]) {
counter = 0; //to loop continuously
}
}
else{
if (counter>0) {
counter--;
NSLog(@"%i", counter);
[stgImage1 setImage:[UIImage imageNamed:[imageStr objectAtIndex:counter]]];
}
}
问题:这部分在我的情况下不起作用,即这里没有发生连续循环
if(counter > [textStr count]) {
counter = 0; //to loop continuously
}
请帮助我!
答案 0 :(得分:0)
问题是你是从< [textStr count]-1
跳到> [textStr count]
而不是评估等于。您也只是在第一个for循环中递增计数器,因此它永远不会在第二个if语句中递增。
-(void)btnClicked:(UIButton*)btn{
if (btn.tag==1) {
NSLog(@"next clicked");
NSLog(@"image array count: %i", [imageStr count]);
counter++;
if (counter == [textStr count]) counter = 0;
NSLog(@"counter: %i", counter);
[stgImage1 setImage:[UIImage imageNamed:[imageStr objectAtIndex:counter]]];
}
else{
NSLog(@"previous clicked");
if (counter>0) {
counter--;
NSLog(@"%i", counter);
[stgImage1 setImage:[UIImage imageNamed:[imageStr objectAtIndex:counter]]];
}
}
}
答案 1 :(得分:0)
9月30日我给出了答案(对于那些可以看到已删除帖子的人:https://stackoverflow.com/questions/19087078/i-want-correct-format-of-this-code)作为要点:https://gist.github.com/vikingosegundo/6814617
您必须确保两个数组具有相同的大小,并且索引在任何时候都有效。如果你使用一些聪明的C代码作为三元运算符和模运算符,你可以大大减少代码。
-(void)btnClicked:(UIButton*)button
{
NSAssert([imageStr count] == [txtStr count], @"both arrays need to have the same number of items");
idx += (button == self.nextButton) ? 1 : -1; // if nextButton increment, else decrement
idx = idx % [textStr count]; // modolo, will keep idx between 0 and count-1
[stgImage1 setImage:[UIImage imageNamed: imageStr[idx]]];
stgText1.text= [NSString stringWithFormat:@"%@", textStr[idx]]];
}