UIButton基本介绍
UIButton 就是一个按钮,他继承UIView 那么就来介绍一下
1:初始化给大小:便利构造器:
//初始化 UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; //设置 Button 的 frame button.frame = CGRectMake(100, 100, 100, 100); //设置背景 button.backgroundColor = [UIColor redColor]; //把他添加到 UIWindow上 [self.window addSubview:button];
2.添加点击事件
// 设置button标题 [button setTitle:@"你点我啊" forState:UIControlStateNormal]; // 点击事件(添加方法) [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside]; //实现方法选择器里面的button响应事件 - (void)buttonAction{ NSLog(@"你打我啊"); }
3.添加背景图片:
[button setBackgroundImage:[UIImage imageNamed:@"11.png"] forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
不同的点击图片改变(类似注册选择)
@property (nonatomic,assign)BOOL flag;
添加点击事件的方法,传入一个参数,参数是这个事件的响应者,参数的类型,是响应者的类型;
- (void)buttonAction:(UIButton *)sender{
if (self.flag == YES) {
[sender setBackgroundImage:[UIImage imageNamed:@"22.png"] forState:UIControlStateNormal];
self.flag = NO;
}else{
[sender setBackgroundImage:[UIImage imageNamed:@"11.png"] forState:UIControlStateNormal];
self.flag = YES;}}
4.外观控制
①:前景色图片
注意:1 覆盖标题 2 不会随着buttonframe进行拉伸 3 前景图片必须是镂空图(好像只有线条的图片)
(1):设置前景色图片:[button1 setImage:[UIImage imageNamed:@"55.png"] forState:UIControlStateNormal];
(2):获取前景色图片:UIImage *image1 = [button1 imageForState:UIControlStateNormal];
②:背景色图片
(1):设置背景色图片:[button1 setBackgroundImage:[UIImage imageNamed:@"11.png"] forState:UIControlStateNormal];
(2):获取背景色图片:UIImage *image2 = [button1 backgroundImageForState:UIControlStateNormal];
③:标题
(1):设置标题:[button1 setTitle:@"点我啊" forState:UIControlStateNormal];
(2):获取标题: NSString *title = [button1 titleForState:UIControlStateNormal];
(3):标题颜色:[button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
④:阴影:[button1 setTitleShadowColor:[UIColor orangeColor] forState:UIControlStateNormal];
⑤:获取颜色:UIColor *color1 = [button1 titleColorForState:UIControlStateNormal];
5.delegate
三部步骤
1,遵循协议,找到当前类(到AppDelegate.h文件中的尖括号+,UITextFieldDelegate)
2,设置代理 操作谁,谁.delegate = self;
3,实现代理方法
代码实例:
//遵循协议 @interface AppDelegate : UIResponder <UIApplicationDelegate,UITextFieldDelegate>
//设置代理 对象.delegate = self;
实现代理(UITextField为例)
- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder];// 释放第一响应者 return YES; // 实现代理方法注意: // 1有返回值 // 2释放第一响应者 }
这个就是 UIButton 的基本内容了!