我有一个数组questionHalf和一个下一个按钮,它调用一个方法nextQuestionButton循环遍历questionHalf数组中的项目并在标签中显示下一个字符串questionLabel
questionHalf = @[@"Atlanta", @"Detroit", @"Houston", @"Green Bay", @"San Francisco"];
可以使用下一个按钮循环:
- (IBAction)nextQuestionButton:(id)sender;
- (IBAction)nextQuestionButton:(id)sender
{
if (currentQuestionIndex < [questionHalf count] -1)
currentQuestionIndex ++;
else currentQuestionIndex = 0;
_questionLabel.text = questionHalf [currentQuestionIndex];
}
然后显示在标签
中@property (weak, nonatomic) IBOutlet UILabel *questionLabel;
我现在想添加5个按钮,让用户从字符串中选择以完成美式橄榄球队的名字。
当用户选择时,我需要查看组合字符串是否是有效的团队名称。
我有另一个数组correctFullAnswer,它包含所有有效的完整团队名称,需要测试用户是否回答匹配此字符串中的一个答案。
correctFullAnswer = @[@"Atlanta Falcons", @"Detroit Lions", @"Houston Texans", @"Green Bay Packers", @"San Francisco 49'ers"];
我还添加了5个必需按钮中的第一个
- (IBAction)packersAnswerButton:(id)sender;
- (IBAction)packersAnswerButton:(id)sender
{
NSString* selectedTeamName = [NSString stringWithFormat:@"%@ %@", questionHalf [currentQuestionIndex], answerHalf];
if ([correctFullAnswer indexOfObject:selectedTeamName] != NSNotFound)
{
[UIView animateWithDuration:0.5 animations:^{
[packersAnswerButton.alpha setAlpha:1];
}
];}
}
但是我现在收到未申报标识符的错误&#39; packersAnswerButton&#39;当我选择正确的答案后,我试图让按钮隐藏。
答案 0 :(得分:0)
只需在要添加按钮的视图中添加5个按钮即可。该过程类似于以下内容:
-(void)viewDidLoad {
//i'm assuming containerView is the view where you are going to add the buttons
NSArray* teamNameSuffices = @[@"Falcons", @"Lions", @"Texans", @"Packers", @"49'ers"];
int i = 0;
for(NSString* suffix in teamNameSuffices) {
UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(<%# your required frame coordinates #>);
btn.titleLabel.text = suffix;
btn.tag = i;
[btn addTarget:self action:@selector(suffixSelected:) forControlEvents:UIControlEventTouchUpInside];
[containerView addSubview:btn];
i++;
}
}
-(void)suffixSelected:(UIButton*)sender {
//here you retrieve suffix text and compare if it is valid team name
NSString* suffix = sender.titleLabel.text;
NSString* selectedTeamName = [NSString stringWithFormat:@"%@ %@",questionHalf [currentQuestionIndex]/* or _questionLabel.text, whichever is accessible */,suffix];
if([correctFullAnswer indexOfObject:selectedTeamName] != NSNotFound) { //a valid team name is constructed
[[[[UIAlertView alloc] initWithTitle:@"Congratulations!" message:@"Bingo!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] autorelease] show];
//or do whatever is required
}
}
您也可以选择从设计器(storyboard / xib)创建后缀按钮,相应地设置其标题,并将其目标设置为suffixSelected:
方法。在这种情况下,您需要将方法声明为(IBAction)
而不是(void)
。
如果您需要探索其他任何内容,请与我们联系。
答案 1 :(得分:0)
可能是你得到的错误。
通过它的外观,您创建了按钮操作。 (IBAction)并将按钮连接到动作。
但可能没有将按钮链接到IBoutlet。
完成后,您将使用它来设置按钮属性。
即
@property IBOutlet (nonatomic) UIButton packersButton;
看看这个苹果文档Interface Builder help