buttonWithType 初始化的时候设置按钮类型
UIButton *btn1=[UIButton buttonWithType:UIButtonTypeCustom];
frame设置按钮位置和大小
btn1.frame=CGRectMake(100, 100, 200, 100) ;
设置按钮背景颜色
btn1.backgroundColor=[UIColor yellowColor];
setTitle :forState 设置按钮文字标题,并且指定在哪种状态下,不同状态下的标题文本也不同
[btn1 setTitle:@"抬起" forState:UIControlStateNormal];
titleLabel.font设置标题字体大小
btn1.titleLabel.font=[UIFont systemFontOfSize:30.f];
setTitleColor :forState 设置标题颜色
[btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
setImage:forState 设置按钮内部小图片
[btn1 setImage:[UIImage imageNamed:@"2"] forState:UIControlStateHighlighted];
setBackgroundImage:forState 设置背景图片
[btn1 setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
setTitleShadowColor :forState 设置阴影颜色
[btn1 setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];
titleLabel.shadowOffset 设置阴影偏移量
- 因为阴影偏移量,无论什么状态都一样,所以不分状态,不用set开头的方法,直接在titleLabel下面.shadowOffset
btn1.titleLabel.shadowOffset=CGSizeMake(1, 2);
.imageView.backgroundColor 设置按钮的图片控件的背景颜色
btn1.imageView.backgroundColor=[UIColor blackColor];//设置按钮的图片控件的背景颜色为黑色
监听点击事件, 给对象绑定方法,当执行某个事件的时候,执行绑定的方法 addTarget: action: forControlEvents:;
target是执行事件的对象,一般是Controller对象
action是处理事件的方法
forControlEvents 是事件类型:
例如下面代码,
target处理的对象是ViewController类对象,这里是self,
action处理方法是:clickBtn: 注意:冒号不能省略,因为下面后面带参数,就要加:冒号
forControlEvents处理事件是鼠标点击UIControlEventTouchUpInside
- (void)viewDidLoad {
//....
[btn1 addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)clickBtn:(UIButton*)sender {
[sender setTitle:@"抬起" forState: UIControlStateNormal];
[sender setBackgroundColor:[UIColor redColor]];
}
下面是获取按钮信息的一些方法getter
titleForState: 获取按钮标题在某个状态下
NSString *strMsg=[_btn1 titleForState:UIControlStateNormal];
titleColorForState 获取按钮文字颜色
UIColor *uc1=[_btn1 titleColorForState:UIControlStateNormal];
imageForState获取按钮内部小图片
UIImage * im1=[_btn1 imageForState:UIControlStateNormal];
backgroundImageForState获取按钮背景图片
UIImage *bg1=[_btn1 backgroundImageForState:UIControlStateNormal];