【问题标题】:Specific action for each buttons in UIScrollViewUIScrollView 中每个按钮的具体操作
【发布时间】:2012-10-09 13:05:35
【问题描述】:

我有一个UIScrollView 页面。在这个UIscrollView 上,我在按钮中有不同的图像,您可以在下面的代码中看到它,我想在按下按钮时将这些图像加载到UIWebView,我的问题是我如何知道单击了哪个按钮。您能否给我一些实现这一点的提示?

我是 Objective-C 的新手

这是我的操作:我想为每张图片设置一个操作,现在我对所有图片只有一个操作,我为每张图片设置一个操作

 - (IBAction)openAction:(id)sender {

  NSLog(@"test");
 }

【问题讨论】:

    标签: objective-c ipad uiscrollview uibutton


    【解决方案1】:

    实际的按钮被传递给 IBAction。在按钮上设置标签是一种方法。如果您在 Interface Builder 中为所有按钮创建了 outlet,您可以简单地执行以下操作:

    - (IBAction)openAction:(id)sender {
        UIButton *b = (UIButton *)sender;
    
        if ([b isEqual:self.outletButton1]) {
            // Do something with button 1
        }
        else if ([b isEqual:self.outletButton2]) {
            // Do something with button 2
        }
    }
    

    【讨论】:

      【解决方案2】:

      不要对按钮使用相同的标签。对不同的按钮使用不同的标签。 例如 [btn setTag:1] 。 你可以使用 [btn setTag:i]; 动态值

      【讨论】:

        【解决方案3】:

        在您的代码或 Interface Builder 中为每个按钮指定一个唯一的标签。

        那么在你的行动中你可以这样做:

        - (IBAction)openAction:(id)sender {
           UIButton *b = (UIButton *)sender;
           NSLog(@"button %d is pressed", b.tag);
        }
        

        我看到你已经给你的 imageviews 标签了。那些不是按钮!您应该创建内容为图像的 UIButton。见 UIButton 的 setImage:forState:

        编辑:针对您的问题,下面是一个示例:

        NSMutableArray *bArray = [NSMutableArray arrayWithCapacity:kNumImages];
        NSUInteger i;
        for (i = 1; i <= kNumImages; i++)
        {
            NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
            UIButton *btn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
            btn setImage:imageName forState:UIControlStateNormal];
            btn.tag = 100+i;
            [bArray addObject:btn];
        }
        

        【讨论】:

        • 谢谢,我怎么知道哪个按钮有哪个图片,请您帮帮我
        • 在您选择图像的 i 循环中,只需将按钮的标签设置为 i(或者更安全,类似 (100+i) 这样您就没有多个标签等于 0.
        【解决方案4】:

        您不必在 UIImageView 上添加 UIButton。相反,您可以像这样为 UIButton 设置图像。

            [btn setImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];
        

        您可以像这样在操作中访问图像:

        - (IBAction)openAction:(id)sender {
          if([[btn currentImage] isEqual:[UIImage imageNamed:@"image1"]]){
        
          }
          NSLog(@"test");
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-19
          • 2021-07-20
          • 2016-01-24
          • 2021-03-02
          • 2014-11-10
          • 1970-01-01
          • 2017-11-04
          相关资源
          最近更新 更多