【问题标题】:choose one button from 4 custom buttons with images从 4 个带有图像的自定义按钮中选择一个按钮
【发布时间】:2013-04-13 00:46:29
【问题描述】:

我在 4 个按钮中有 4 个图像:imag01.jpgimag02.jpgimag03.jpgimag04.jpg 和 4 个声音:sound01.aifcsound02.aifcsound03.aifcsound04.aifc

我正在生成 4 个这样的按钮:

UIButton *oneButton = [UIButton buttonWithType:UIButtonTypeCustom];
[oneButton setTitle:@"1" forState:UIControlStateNormal];
[oneButton setTitle:@"1" forState:UIControlStateHighlighted];

[oneButton setImage:[UIImage imageNamed:@"imag01.jpg"] forState:UIControlStateNormal];
[oneButton setImage:[UIImage imageNamed:@"imag01.jpg"] forState:UIControlStateHighlighted];
oneButton.frame = CGRectMake(20, 100, 140, 100);

[scrMain addSubview:oneButton];

我想生成一个从 1 到 4 的随机数(例如 3),播放与之相关的声音 (sound03.aifc) 并要求用户为该声音按下正确的按钮 (imag03.jpg)。

如何在按钮和声音之间建立联系?

【问题讨论】:

  • 与其要求指向示例代码的指针(“资源请求”问题),不如在 SO 上解释您的问题并寻求解决方案的帮助。这样,当其他人遇到类似问题时,这里的答案也可以帮助他们。我已经稍微编辑了您的问题以反映这一点 - 如果您认为需要,请查看并修改。

标签: ios objective-c uiimageview uibutton arc4random


【解决方案1】:

这样做:

  • 为每个按钮的tag 属性分配从 0 到 3 的不同值。

  • 将声音放入数组中。

  • 生成一个介于 0 和 3 之间的随机整数,包括 0 和 3。使用它作为索引从数组中检索声音。播放那个声音。

  • 启用 4 个按钮并要求用户点击相应的按钮。

  • 如果按钮的tag 属性与您选择的数字匹配,万岁!干得好,用户!

  • 否则,太糟糕了!再试一次。

【讨论】:

  • 直到第 5 步,我已经拥有了我需要的东西。我如何检查整数和我认为不是整数的标签属性之间的对应关系?
  • tag 确实是NSInteger
  • @Mihai Tags are NSIntegers。如果所有四个按钮都向同一个目标发送相同的操作,只需说if (sender.tag == theSoundIndex) { [self tellUser:@"HOORAY!"] }
  • 我在每个按钮后都有这个 [scrMain addSubview:oneButton]; [oneButton addTarget:self action:@selector(onButtonPressCorrect) forControlEvents:UIControlEventTouchUpInside];和 -(IBAction)onButtonPressCorrect:(id)sender{ } 你指的是什么 sender.tag?
  • 找到了,这是语义问题,我不得不使用“if ([sender tag] == theSoundIndex)”。非常感谢 Caleb,非常感谢您的帮助!
【解决方案2】:

查看此问题的答案以生成 0 到 3 之间的随机数:Generating random numbers in Objective-C

如果你不打算从零开始索引你的按钮,你可以简单地在结果中加一。

【讨论】:

    【解决方案3】:

    这实际上用 NSArray 很容易做到。为了便于理解,让我们创建两个数组。

    一个用于图像,一个用于声音。

    NSArray* buttonImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"imag01.jpg"],
                          [UIImage imageNamed:@"imag02.jpg"],[UIImage imageNamed:@"imag03.jpg"][UIImage imageNamed:@"imag04.jpg"],  nil];
    
    NSArray* buttonSounds = [NSArray arrayWithObjects:[same idea as the uiimage, i don\'t know what you are using to load sound],  nil];
    

    然后使用arc4random生成随机数:

    int randomNumber = arc4random()%4;
    

    然后用你刚刚生成的数字调出一个图像和声音并将其应用到uibutton

    UIImage* image = [buttonImages objectAtIndex:randomNumber];
    [oneButton setImage:image forState:UIControlStateNormal];
    

    再次对声音做同样的事情,并根据我们刚刚生成的randomNumber 附加声音的属性。只需确保图像阵列和声音阵列根据哪个图像是正确的声音排列。

    我无法为您编写生成随机声音的代码,因为我不明白您是如何加载声音的。所以我以 UIImages 为例。因此,为了指出正确的方向,将 UIImage 代码替换为声音代码,以应用相同的想法。

    要检查声音是否匹配,我会检查[buttonSound objectAtIndex:randomNumber]; 是否等于用户按下的按钮上的那个。

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 2013-09-03
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多