UIButton按钮类的使用
我要说什么?1. 什么是按钮
2. 按钮的基本使用
知识点详解
1. 什么是按钮?
如下如所示, 我们很多时候需要在让用户控制我们的应用, 一般可以使用按钮
2. 按钮的使用
//按钮类UIButton的使用//1.如何创建一个按钮//创建按钮UIButton *button =[UIButton buttonWithType:UIButtonTypeSystem];//设置位置button.frame = CGRectMake(100,100,100,30);//设置文本[button setTitle:@"点我啊"forState:UIControlStateNormal];
[self.window addSubview:button];//说明1: 按钮一般使用buttonWithType这个类方法创建, 参数为按钮的类型//最常常用的有如下两种类型//<2>UIButtonTypeCustom 图片按钮//<1>UIButtonTypeSystem 系统按钮//说明2: 设置显示的文本时候参数2为状态//常用的是 UIControlStateNormal表示正常状态//说明3://ios6: 默认就是圆角矩形按钮//ios7: 所有按钮没有边框了(扁平化)//告诉按钮: 被点了应该执行那个方法//forControlEvents 控件事件类型//常用事件: 按下弹起//addTarget和action表示由那个方法去处理这个事件[button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];//2.设置文本颜色[button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];//3.设置字体button.titleLabel.font = [UIFont systemFontOfSize:24];//4.禁用按钮(NO表示禁止)button.enabled =YES;//5.被点击时的高亮效果button.showsTouchWhenHighlighted =YES;//6.设置Tag值//每个控件都有tag这个属性//给这个属性赋任意的值,区分不同的控件//10个按钮的事件处理方法都是一个button.tag =100;//7.实现带图片的按钮UIButton *imageButton=[UIButton buttonWithType:UIButtonTypeCustom];
imageButton.frame= CGRectMake(100,200,100,30);//注意: 使用的图片资源拷入工程即可UIImage *image = [UIImage imageNamed:@"back.png"];//按钮添加背景图片[imageButton setBackgroundImage:image forState:UIControlStateNormal];//设置文本左边的图片[imageButton setImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];//8.设置按钮中图片和文本的偏移(位置)//UIEdgeInsets//top, left, bottom, right//可以控制图片和文本与按钮上边,左边,底边和右边的距离imageButton.imageEdgeInsets = UIEdgeInsetsMake(0,60,0,0);
imageButton.titleEdgeInsets= UIEdgeInsetsMake(0, -60,0,0);
[self.window addSubview:imageButton];
[imageButton addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[imageButton setTitle:@"点我呀"forState:UIControlStateNormal];
self.window.backgroundColor=[UIColor grayColor];
[self.window makeKeyAndVisible];returnYES;
}//为了按钮添加一个点击事件的处理方法//参数: 是固定的, 参数就是事件的来源-(void)btnClick//-(void)btnClick:(UIButton *)button{//NSLog(@"我被点了.....");//弹出一个对话框UIAlertView *alertView =[[UIAlertView alloc] init];
alertView.message=@"按钮被点了";
[alertView addButtonWithTitle:@"取消"];
[alertView show];
}