UIButton的selected狀態

設置button的selected狀態下image和title的時候,要注意,本身對按鈕的點擊是不會改變selected狀態的,需要我們在按鈕的監聽方法裏去對這個值設置,纔會觸發到不同狀態下

下面代碼是通過button做的一個簡易的複選框

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

- (void)loadView{

    self.view = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    [button setFrame:CGRectMake((self.view.bounds.size.width-180)/2, (self.view.bounds.size.height-44)/2, 180, 44)];

    //normal

    [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"login_checkbox_normal.png"]] forState:UIControlStateNormal];

    [button setTitle:@"點我啊" forState:UIControlStateNormal];

    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [button.titleLabel setFont:[UIFont systemFontOfSize:17]];


    [button addTarget:self action:@selector(tapButton:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

}

- (void)viewDidLoad {

    [super viewDidLoad];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}

#pragma mark - 按鈕點擊事件

- (void)tapButton:(UIButton *)button{

    [button setSelected:!button.isSelected];

    if (button.isSelected) {

         //selected

        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"login_checkbox_checked.png"]] forState:UIControlStateSelected];

        [button setTitle:@"臥槽你真點" forState:UIControlStateSelected];

        [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];

        [button.titleLabel setFont:[UIFont systemFontOfSize:17]];


    }else{

        //normal

        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"login_checkbox_normal.png"]] forState:UIControlStateNormal];

        [button setTitle:@"點我啊" forState:UIControlStateNormal];

        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

        [button.titleLabel setFont:[UIFont systemFontOfSize:17]];


    }

}

@end



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章