天天看点

UI02_UIButton

总结

前期准备工作与UILabel相同
           
创建一个Button
  ()Button用自己的便利构造器的方式来创建对象,而且button不用release
  ()UIButton *button=[UIButton buttonWithType:UIButtonTyprSystem];
           
2.指定Button的位置和大小
button.frame=CGRectMake(100,100,100,40);
           
3.设置背景颜色
button.backgroundColor=[UIColor redColor];
           
将button挂在window上
[self.window addSubview:button];
           
.设置标题
[button setTitle:@"确认"forState:UIControlStateNormal];
           
设置标题字体大小
button.titleLabel.font=[UIFont systemFontOfSize:];
           
设置圆角
button.layer.cornerRadius=;
           
设置边框
button.layer.borderWidth=;
           
点击方法
  这是button最重要的部分  sel是方法选择器   首先是@select
  [button addTarget:self action:@selector(click:)forControlEvents:UIControlEventTouchUpInside]; 
  建立click方法
  -(void)click:(UIButton *)button
  {
    NSLog(@"点击");
  }
           
更换button内容

  UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
  button.frame=CGRectMake(,,,);
  [self.window addSubview:button];
  [button setTitle:@"确认"forState:UIControlStateNormal];
  button.layer.cornerRadius=;
  button.layer.borderWidth=;
  [button addTarget:self action:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
  //设置tag就是为后面的父类找到对应的子类,方便对子类进行设置
 button.tag=;

  click方法实现部分
{
//等号后面加(UIButton *)的原因是window本身是UIView.虽然有继承关系,但是为了类型统一我们还是在此处对他进行类型的转换.保证类型的统一.
UIBuuton *but=(UIBuuton *)[self.window viewWithTag:];
//判断当前按钮的标题
//获取当前按钮的标题
NSLog(@"%@",but.currentTitle);//点击时获取button的内容
if([button.currentTitle isEqualToString:@"确认"])
{
[but setTiltle:@"取消"forState:UIControlStateNormal];

}
}
 //将确认改成取消 
           
点击更换图片
前述:
     ()给button设置图片用image(图片)
     ()图片大小会自动适应button的设置边框,边框多大,图片就多大
     ()将图片添加方法里不是像OC拽文件那样取得路径就可以了,而是把图片名字输入到里面

设置一个属性BOOL类型
@property (nonatomic,assign)BOOL isClick;
实现部分:
UIButton *button=[UIBuutton buttonWithtype:UIButtonTypeSystem];
button.frame=CGRectMake(,,,);
[self.window addSubview:button];
[button addTarget:self action:@selector(change Pic:)forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:@"BtfOff.png"]forState:UIControlStateCustom];
//如果想使用setImage设置图片的话.button的类型要调整成custom.setImage方法不会把图片方法成按钮大小

changePic方法:更换按钮背景图
-(void)changeImage:(UIButton *)button{
//判断
if(self.isClick){
[button seyImage:[UIImage imageNamed:@"BtnOn.png"]forState:UIContolStateNormal];
}else{
[button setImage:[UIImage imageNamed:@"BtnOff.png"forState:UIControlStateNormal];
     }
 //对当前的状态进行调整
self.isClick=!self.isClick;
}

//按钮的点击方法会传过来一个相应类型的button.谁触犯了这个点击方法,相应的button就是那个对象