动态添加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/
*************************************************************************/
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 百万级群聊的设计实践
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)