1 @interface ViewController () 2 - (IBAction)customBtnClick; 3 4 @end 5 6 @implementation ViewController 7 8 - (void)viewDidLoad { 9 [super viewDidLoad]; 10 // Do any additional setup after loading the view, typically from a nib. 11 12 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 13 14 // 1.设置标题 15 // btn.titleLabel.text = @"我是按钮"; // 千万不要这样写 16 // 一般情况下给按钮设置内容都是setXXX 17 [btn setTitle:@"我是按钮" forState:UIControlStateNormal]; 18 [btn setTitle:@"哥是高亮" forState:UIControlStateHighlighted]; 19 20 // 2.设置标题颜色 21 // btn.backgroundColor = [UIColor redColor]; 22 [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 23 24 // 3.设置图标 25 [btn setImage:[UIImage imageNamed:@"common_icon_check"] forState:UIControlStateNormal]; 26 27 // 4.设置背景图片 28 [btn setBackgroundImage:[UIImage imageNamed:@"common_button_big_blue_highlighted"] forState:UIControlStateNormal]; 29 30 // 5.监听按钮的点击 31 // Target:让谁监听按钮 32 // action:监听到之后需要执行的方法 33 // Events:事件的类型 34 // 规律: 只要是继承于UIControl的控件, 都可以通过addTarget来添加监听 35 [btn addTarget:self action:@selector(customBtnClick) forControlEvents:UIControlEventTouchUpInside]; 36 37 // UISwitch sw = nil; 38 // [sw addTarget:<#(nullable id)#> action:<#(nonnull SEL)#> forControlEvents:<#(UIControlEvents)#>] 39 40 // UISegmentedControl *sc = nil; 41 // [sc addTarget:<#(nullable id)#> action:<#(nonnull SEL)#> forControlEvents:<#(UIControlEvents)#>] 42 43 // UITextField *tf = nil; 44 // [tf addTarget:<#(nullable id)#> action:<#(nonnull SEL)#> forControlEvents:<#(UIControlEvents)#>] 45 46 btn.titleLabel.font = [UIFont systemFontOfSize:14]; 47 btn.frame = CGRectMake(100, 100, 100, 100); 48 [self.view addSubview:btn]; 49 } 50 51 - (IBAction)customBtnClick { 52 NSLog(@"%s", __func__); 53 } 54 @end