【问题标题】:Objective-C Loop through an array with a button?Objective-C 用一个按钮循环遍历一个数组?
【发布时间】:2016-09-28 22:57:36
【问题描述】:

我在班级Questions 中有一系列问题 (NSArray *questions)。我在视图上有一个标签 (questionLabel) 和一个按钮 (nextButton)。当按下按钮时,我希望标签循环遍历问题数组。我在 Treehouse 上做了类似的事情,但他们使用了 arc4random,这看起来不太好,因为相同的问题在更改之前可能会连续出现多次。我想通过问题数组按顺序无限循环。我已经复制了下面按钮的代码。

应用程序运行,但当我按下按钮时没有任何反应。老实说,我花了两个星期的时间搜索、学习等,但我没有发现任何东西可以帮助我解决这个问题。非常感谢任何帮助。

这段代码在 ViewController.m 文件中:

- (IBAction)nextButton {
   NSArray *questions = [[NSArray alloc] init];
   for (NSString *nextQuestion in questions) {
       self.questionLabel.text = nextQuestion;
   }
}

【问题讨论】:

  • 为什么要在点击按钮时执行循环?您只想将文本设置为下一个问题,而不是所有问题。

标签: objective-c arrays for-loop uibutton uilabel


【解决方案1】:

我不确定我是否完全理解您的问题,
您想看到的结果是这样的吗?

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UILabel *questionLabel;
@property (nonatomic, strong) NSArray *questions;
@end

@implementation ViewController
@synthesize questions;
@synthesize questionLabel;

- (IBAction)nextButton:(id)sender {

    /* 
        this does alloc init and return array object containing no index data.
     */
    // questions = [[NSArray alloc] init];

    for (NSString *nextQuestion in questions) {
        self.questionLabel.text = nextQuestion;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    questions = [[NSArray alloc] initWithObjects:@"Question1", @"Question2", @"Question3", @"Question4", nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


在这种情况下,您当然会在数组对象索引中得到零数据。

在您的代码中,

- (IBAction)nextButton {
   NSArray *questions = [[NSArray alloc] init];
   for (NSString *nextQuestion in questions) {
       self.questionLabel.text = nextQuestion;
   }
}

这会分配 / 初始化,并在单击按钮时返回包含空索引数据的 NSArray 引用,并且循环遍历空索引数据数组对象。

===========================================
编辑和更新
===========================================

//
//  ViewController.m
//  StackoverflowQuestion
//
//  Created by Seoksoon Jang on 29/09/2016.
//  Copyright © 2016 Seoksoon Jang. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UILabel *questionLabel;
@property (strong, nonatomic) IBOutlet UIButton *questionButton;
@property (nonatomic, strong) NSArray *questions;
@property (nonatomic, assign) BOOL stopRequest;
@end

@implementation ViewController
@synthesize questions;
@synthesize questionLabel;
@synthesize questionButton;
@synthesize stopRequest;

#define LOOP_DELAY_TIME     0.1

- (UIColor*)generateRandcomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return randomColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

- (IBAction) stopButton:(id)sender {
    stopRequest = !stopRequest;
}

- (IBAction) nextButton:(id)sender {

    self.questionButton.enabled = NO;

    for (NSString *nextQuestion in questions) {

        dispatch_async(dispatch_get_main_queue(), ^{
            self.questionLabel.text = nextQuestion;
            self.questionLabel.backgroundColor = [self generateRandcomColor];
        });

        [NSThread sleepForTimeInterval:LOOP_DELAY_TIME];
    }

    if (stopRequest) {
        stopRequest = !stopRequest;

        dispatch_async(dispatch_get_main_queue(), ^{
            self.questionButton.enabled = YES;
        });

        return ;

    } else {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self performSelector:@selector(nextButton:) withObject:nil];
        });
    }
}

- (void) viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    questions = [[NSArray alloc] initWithObjects:@"Why is Kimchi the best food in the world", @"Why is Bacon healthy?", @"Why is Pizza delicious?", @"Why is Tuna nice?", nil];    
}

- (void) didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

这是如此简单的UI界面和基于此源代码的结果截图。


* Storyboard UI 示例截图 *




* 结果 *

===========================================
编辑和更新 2
===========================================

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UILabel *questionLabel;
@property (strong, nonatomic) IBOutlet UIButton *questionButton;
@property (strong, nonatomic) NSArray *questions;
@property (assign, nonatomic) NSUInteger count;
@end

@implementation ViewController
@synthesize questions;
@synthesize questionLabel;
@synthesize questionButton;
@synthesize count;

- (IBAction)nextButton:(id)sender {

    if (count >= [questions count]) {
        count = 0;
    }

    self.questionLabel.text = [questions objectAtIndex:count++];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    questions = [[NSArray alloc] initWithObjects:@"Question1", @"Question2", @"Question3", @"Question4", nil];

    count = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

抱歉,您的问题弄错了。
可能,这又不是您想要的。
我只是为了好玩。所以,不要觉得累赘。

【讨论】:

  • 非常感谢您花时间整理这些内容。因此,我完全按照您的建议应用了代码,但是当我按下按钮时,它只会将标签带到数组中的最后一个对象。当我按下按钮时,我希望标签无限地遍历数组。你觉得你能帮我解决这个问题吗?再次感谢!
  • 好的,在编辑过的源代码中,我尝试过,据我了解您的问题。无论如何,这个请求是否符合您的要求?
  • 再次感谢您花时间写这篇文章,但我想要的唯一区别是单击 - 下一个问题,单击 - 下一个问题,单击 - 下一个问题等。那有意义吗?因此,用户单击按钮以一次获取数组中的下一个问题。但就像我说的那样,我可以使用 arc4random 来做到这一点,但同样的问题会连续出现多次。
  • 单击 - 下一个问题,单击 - 下一个问题,单击 - 下一个问题...单击 - 下一个问题通过循环迭代?你能给我你的源代码或项目链接吗?
  • 太完美了!谢谢,这正是我想要按钮做的。现在我需要弄清楚如何将数组放入一个新类中,因为我打算用不同的问题包制作几个数组,所以我认为我应该将这些数组放在一个类中。再次感谢 boraseoksoon!
【解决方案2】:

我希望你这样做

在接口声明中

int i,j;
NSArray questions;

现在在 viewdidload 中并将所有对象添加到数组中

j=0;
i=j;
questions = [[NSArray alloc]initwithObjects : "YOUR QUESTION","YOUR QUESTION"..........,nil];

现在在按钮操作方法中

-(IBAction)nextButton : (sender)
{
     for (i = j; i < [questions count]; i++)
     {
        self.questionLabel.text = [quesions objecAtIndex:i];  
        j = i;
        break;
     } 
}

希望这件事有效

【讨论】:

  • 非常感谢您将这些放在一起。我也完全按照您的建议进行了尝试,但是该按钮只是将标签更改为数组中的一个对象,而不是遍历整个数组。对此有任何修复吗?谢谢!
  • 主要是你想要什么?根据我的理解,您希望每次单击按钮时都更改问题。所以据此我的代码工作正常
  • 对不起,我的意思是当我单击按钮时,它只会停在数组中的一个对象上,然后当我再次单击它时,什么也没发生,所以它会卡在一个对象上。我希望它一次点击一个问题。
猜你喜欢
  • 2013-11-06
  • 1970-01-01
  • 2018-04-09
  • 2013-11-05
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多