UIButton在代码中使用及点击事件

UIButton在代码中使用及点击事件

主要代码

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    创建button
//    注:设置类型只能在初始化的时候
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    设置frame
    button.frame = CGRectMake(100, 100, 170, 44);
//    设置背景颜色,分状态
    button.backgroundColor = [UIColor redColor];
    [button setTitle:@"普通Button" forState:UIControlStateNormal];
    [button setTitle:@"高亮Button" forState:UIControlStateHighlighted];
//    设置文字颜色,分状态
    [button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
    //    设置文字阴影,分状态
    [button setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
     [button setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//    设置文字偏移量
    button.titleLabel.shadowOffset = CGSizeMake(3, 2);
//    设置内容图片,分状态
    [button setImage:[UIImage imageNamed:@"power_normal.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"power_pressed.png"] forState:UIControlStateHighlighted];
//    设置button的imageview的背景
    button.imageView.backgroundColor = [UIColor purpleColor];
//    //    设置Button背景图片,分状态
//   [button setBackgroundImage:[UIImage imageNamed:@"power_bg_img_normal.png"] forState:UIControlStateHighlighted];
//    [button setBackgroundImage:[UIImage imageNamed:@"power_bg_img_pressed.png"] forState:UIControlStateHighlighted];
//    添加到ViewController中去
    [self.view addSubview:button];

//    Button监听事件,非常重要
    /**
     *addTarget:目标(让谁做这个事情)
     *action:方法(做什么事情-->方法)
     *forControlEvents:事件
     */
    [button addTarget:self action:@selector(demo:) forControlEvents:UIControlEventTouchUpInside];

}
-(void)demo:(UIButton *) button{
    NSLog(@"%@",button);
}
-(IBAction)clickButton:(UIButton *)button{
    NSLog(@"%@",button);
    button.enabled = NO;
}

你可能感兴趣的:(ios)