-3

我知道这个问题被问了很多次,但我没有找到任何解决我的问题的方法。我在 ViewDidLoad 上声明计数器为 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
}

请帮我!

4

2 回答 2

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]]];
}
于 2014-02-28T20:38:42.103 回答
0

问题是您从< [textStr count]-1to跳过> [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]]];
     }
   }
}
于 2013-11-15T07:28:06.100 回答