UIButton小记

UIButton

UIButton 继承自 UIControl

UIButton是一个复合视图

1.初始化

创建时可选的几种  UIButtonType

typedef NS_ENUM(NSInteger, UIButtonType) {
    UIButtonTypeCustom = 0,                         // no button type
    UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),  // standard system button
    
    UIButtonTypeDetailDisclosure,
    UIButtonTypeInfoLight,
    UIButtonTypeInfoDark,
    UIButtonTypeContactAdd,
    
    UIButtonTypeRoundedRect = UIButtonTypeSystem,   // Deprecated, use UIButtonTypeSystem instead
};

初始化
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];

设置alpha值CGFloat类型,取值范围是 0.0~1.0
button.alpha = 0.4;

2.设置属性

  • 1、设置颜色

    button.backgroundColor = [UIColor cyanColor];

  • 2、设置frame,也就是设置button的坐标以及大小

    button.frame = CGRectMake(20, 100, 280, 50);

  • 3、设置状态 ​ /* (UIControlState)
    typedef NS_OPTIONS(NSUInteger, UIControlState) { 正常 UIControlStateNormal = 0,

         高亮  	    
         UIControlStateHighlighted  = 1 << 0,        	         	         // used when UIControl isHighlighted is set
           
         不可用
    	  UIControlStateDisabled     = 1 << 1,
    
    选中 UIControlStateSelected 默认YES UIControlStateSelected = 1 « 2, // flag usable by app (see below) 当应用程序标志时使用
    	  UIControlStateApplication  = 0x00FF0000,              // additional flags available for application use
      	  
    	   为内部框架预留
       	   UIControlStateReserved     = 0xFF000000               // flags reserved for internal framework use
    
    } 以上几种用的一般是前几种。 例: button.selected = YES; // 默认为 NO(未选中)
    [button setTitle:@”被选中” forState:UIControlStateSelected]; button.enabled = NO; // 默认为YES [button setTitle:@”不可用” forState:UIControlStateDisabled]; [button setTitle:@”点我” forState:UIControlStateNormal];
  • 4、设置字体

    button.titleLabel.font = [UIFont systemFontOfSize:20.0];

  • 5、给按钮上的字设置颜色

    button.tintColor = [UIColor whiteColor];

  • 6、设置图片

    UIImage 图片类,继承自 NSObject ​ 通过路径添加图片 [button setImage:[UIImage imageWithContentsOfFile:@”/Users/klone/UIButton/demo.png”] forState:UIControlStateNormal];

    工程下通过直接添加,png格式的图片在添加时可以直接省略文件格式名(后缀) UIImage *img = [UIImage imageNamed:@”demo”]; [button setImage:img forState:(UIControlStateNormal)]; 将img以背景图显示 [button setBackgroundImage:img forState:UIControlStateNormal];
  • 7、添加时间相应

    target:指定相应的对象 action:指定对象的响应方法 event:事件的触发时机 事件方法可以跟参数,而且只能跟一个 [button addTarget:(id) action:(SEL) forControlEvents:(UIControlEvents)] [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];

3.添加到父视图

		[self.window addSubview:button];

触发按钮响应的方法:

		- (void)buttonAction{
			NSLog(@"hi,you");
		} ​