iOS之UIButton的使用

1.创建

1 @property(nonatomic, strong) UIButton *btn;
 1 //1.不常用
 2     self.btn = [[UIButton alloc]initWithFrame:CGRectMake(50, 100, 200, 50)];
 3     //2.常用这种方法(上面那种可舍弃不用)
 4     self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
 5     /*
 6      UIButtonTypeCustom = 0,//自定义类型
 7      UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),//系统类型
 8      
 9      UIButtonTypeDetailDisclosure,//详细描述样式(圆圈中间加个i)
10      UIButtonTypeInfoLight,//浅色的详细描述样式
11      UIButtonTypeInfoDark,//深色的详细描述样式
12      UIButtonTypeContactAdd,//加号样式
13      
14      UIButtonTypeRoundedRect = UIButtonTypeSystem,//圆角矩形
15      };
16 
17      */

2.设置大小

 _btn.frame = CGRectMake(50, 50, 200, 100);

3.设置背景

1 //设置背景颜色
2     [self.btn setBackgroundColor:[UIColor orangeColor]];
3     //设置背景图片
4     [self.btn setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];

4.设置标题

/*
     注:前四个用的多一点
     UIControlStateNormal        //正常状态下(这个用的最多)
     UIControlStateHighlighted   //高亮状态下(按钮按下还未抬起的时候)
     UIControlStateDisabled      //禁用状态下
     UIControlStateSelected      //选中状态下
     
     UIControlStateApplication   //当应用程序标志时
     UIControlStateReserved      //为内部框架预留
     */
    
    [_btn setTitle:@"编辑" forState:UIControlStateNormal];
    
    
    //设置标题颜色
    [_btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    

5.给按钮添加事件

//如果事件有参数 只能是UIButton类型
    //当按钮的一个事件被触发了,系统会将这个按钮对象作为参数传递给事件
    /*
     UIControlEventTouchDown  按下去就会响应
     UIControlEventTouchUpOutside 点下去没反应 在该范围内放手才有响应(一般用这个)
     */
    [_btn addTarget:self action:@selector(changTitle) forControlEvents:UIControlEventTouchDown];
    [_btn addTarget:self action:@selector(changTitle) forControlEvents:UIControlEventTouchUpOutside];
    

改变按钮的标题的方法(3个)

- (void)changTitle:(UIButton *)sender{
    
    //改变按钮的标题(有三个方法)
    //1.property属性: _btn 或者  self.btn  访问
    //得到按钮标题
    if([_btn.titleLabel.text isEqualToString:@"编辑"]){
        [self.btn setTitle:@"完成" forState:UIControlStateNormal];
    } else{
        [self.btn setTitle:@"编辑" forState:UIControlStateNormal];
    };
    
    //2.tag值
    UIButton *button = [self.view viewWithTag:1];
    
    
    //3.作为参数直接传递过来(这种方式用的比较多)
    //addTarger
}

猜你喜欢

转载自www.cnblogs.com/frosting/p/9462605.html
今日推荐