zoukankan      html  css  js  c++  java
  • 动态添加UIButton控件,通过设置tag值实现点击不同的UIButton控件做出不同的反应

    在上一篇博文《在滚动视图里添加图像视图,在图像视图里添加按钮控件》的基础上做了小小的改动。

    》》点击button1》》

    》》点击button2》》

    需要改写两个地方:

    @synthesize scrollView = _scrollView;
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        // 配置 UIImageView 对象
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"]];
        imgView.userInteractionEnabled = YES;  // UIImageView 的 userInteractionEnabled 属性默认 "NO",因此默认情况下,添加在 UIImageView 中的 UIButton 将不发生触摸事件
        
        // 配置并添加 UIButton 对象
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button1.frame = CGRectMake(100, 80, 40, 40);
        [button1 setTitle:@"Button1" forState:UIControlStateNormal];
        
        button1.tag = 100;      // 1、分别设置tag
        
        [button1 addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        [imgView addSubview:button1];
        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button2.frame = CGRectMake(200, 80, 40, 40);
        [button2 setTitle:@"Button2" forState:UIControlStateNormal];
        
        button2.tag = 200;      // 1、分别设置tag
        
        [button2 addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        [imgView addSubview:button2];
        
        // 添加 UIImageView 对象
        [self.scrollView addSubview:imgView];
        
        // 配置 UIScrollView 对象
        self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
        self.scrollView.scrollEnabled = YES;
        self.scrollView.clipsToBounds = YES;
        self.scrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height);
        
    }
    
    - (IBAction)button:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        
        // 2、通过tag进行选择对应的操作
        if (button.tag == 100) {
            [self performSegueWithIdentifier:@"SeguePush" sender:self];
        } else {
            NSLog(@"button2");
        }
    }


    /**************************************************************************
                      原文来自博客园——Submarinex的博客: www.cnblogs.com/submarinex/               
      *************************************************************************/

  • 相关阅读:
    [算法笔记] 扩展欧几里得算法
    [算法笔记] 数学基础
    [算法] 动态规划 (2)
    [算法笔记] 图论总结
    最简单的数据库入门教程—04—00—关系数据库
    最简单的数据库入门教程—03—数据库系统体系
    最简单的数据库入门教程—02—数据模型
    最简单的数据库入门教程—01—数据库系统概论
    最简单的数据库入门教程—00—数据库导论
    数据可视化分析
  • 原文地址:https://www.cnblogs.com/submarinex/p/2806269.html
Copyright © 2011-2022 走看看