Object-c 创建按钮

本文详细介绍了如何在iOS应用开发中使用Objective-C动态创建UIButton,并设置了按钮的文字、颜色及背景图片,同时添加了点击事件处理。
@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

 

转载于:https://www.cnblogs.com/kingBook/p/6655229.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值