@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //动态创建我们自己的按钮 //1.创建按钮(UIButton) UIButton *button = [[UIButton alloc]init]; //2.设置按钮上显示的文字 [button setTitle:@"点我吧" forState:UIControlStateNormal]; [button setTitle:@"摸我干啥" forState:UIControlStateHighlighted]; //设置文字颜色 [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; [button setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted]; //3.加载图片 UIImage *imgNormal = [UIImage imageNamed:@"btn_01"]; UIImage *imgHighlighted = [UIImage imageNamed:@"btn_02"]; //4.设置背景图片 [button setBackgroundImage:imgNormal forState:UIControlStateNormal]; [button setBackgroundImage:imgHighlighted forState:UIControlStateHighlighted]; //5.设置frame属性(位置和大小) button.frame = CGRectMake(50, 50, 100, 100); //6.通过代码为控件注册一个单机事件 [button addTarget:self action:@selector(buttonPrint) forControlEvents:UIControlEventTouchUpInside]; //7.把动态创建的控件添加到控制器的view中 [self.view addSubview:button]; } - (void)buttonPrint{ printf("测试打印"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
本文详细介绍了如何在iOS应用开发中使用Objective-C动态创建UIButton,并设置了按钮的文字、颜色及背景图片,同时添加了点击事件处理。
3049

被折叠的 条评论
为什么被折叠?



