1.创建UIButton对象(使用便利构造器方法)
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];2.配置属性
注意:一定要配置frame
btn.frame = CGRectMake(30, 200, 70, 30);btn.backgroundColor = [UIColor redColor];
(1)添加文字
// [_button1 setTitle:@"登陆" forState:UIControlStateNormal];
// [_button1 setTitle:@"denglu" forState:UIControlStateHighlighted];
// [_button1 setTitle:@"选中" forState:UIControlStateSelected];
(2)添加点击事件
[btn addTarget:self action:@selector(clickButton1) forControlEvents:UIControlEventTouchUpInside];
//移除点击事件
//[_button1 removeTarget:self action:@selector(clickButton1) forControlEvents:UIControlEventTouchUpInside];
//************外观设置************
/*
//(3)获取指定状态下的标题
NSString *title = [_button1 titleForState:UIControlStateNormal];
NSLog(@"普通状态的标题: %@",title);
NSString *title1 = [_button1 titleForState:UIControlStateHighlighted];
NSLog(@"高亮状态下的标题%@",title1);
//(4)设置某个状态下的titlecolor
[_button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//(5)设置title字体大小
_button1.titleLabel.font = [UIFont systemFontOfSize:20];
//(6)设置title指定状态下的阴影颜色
[_button1 setTitleShadowColor:[UIColor blueColor] forState:UIControlStateNormal];
_button1.titleLabel.shadowOffset = CGSizeMake(3, 3);
//(7)获取颜色值
UIColor *naomalColor = [_button1 titleColorForState:UIControlStateNormal];
NSLog(@"%@",naomalColor);
*/
//(8)设置图片在某个状态下
//[_button1 setImage:[UIImage imageNamed:@")19HYJL{YKYCB}4OL8ADFMM.png"] forState:UIControlStateNormal];
//UIImage *normalImage = [_button1 imageForState:UIControlStateNormal];
//NSLog(@"%@",normalImage);
[btn setBackgroundImage:[UIImage imageNamed:@"]W4FQLLLVU69EHM8X0@$U$O"] forState:UIControlStateNormal];
(9)当按钮高亮或者禁用,UIButton 类可以调整自己的外观,下面几个属性可以让你按照需要对按钮的外观进行微调:
默认情况下,在按钮被禁用时,图像会被画的颜色深一些。要禁用此功能,将这个属性设置为NO:
btn1.adjustsImageWhenHighlighted = NO;
默认情况下,按钮在被禁用时,图像会被画的颜色淡一些。要禁用此功能,请将这个属性设置为NO:
btn1.adjustsImageWhenDisabled = NO;
这个属性设置为YES,可令按钮在按下时发光。这可以用于信息按钮或者有些重要的按钮:
btn1.showsTouchWhenHighlighted = YES;
3.有些情况会是button的点击事件失效
(1).button.hidden = true;
(2).button.alpha = 0;
(3).父控件或者自身的userInteractionEnabled属性为false(特别有可能发生于两层view叠加中)
补充一下,以下内容转载于:
UIbutton 详解 FireFrog http://1.firefrog.sinaapp.com/?p=570
可以通过子类化按钮来定制属于你自己的按钮类。
在子类化的时候你可以重载下面这些方法,这些方法返回CGRect,控制按钮每一组成部分的边界。
注意:不要直接调用这些方法, 这些方法是你写给系统调用的。
backgroundRectForBounds //指定背景边界
contentRectForBounds // 指定内容边界
titleRectForContentRect // 指定文字标题边界
imageRectForContentRect //指定按钮图像边界
例:
- (CGRect)imageRectForContentRect:(CGRect)bounds{
return CGRectMake(0.0, 0.0, 44, 44);
}
}