天天看點

ios 巧用UIButton的UIControlStateSelected屬性

一般可以巧用UIBUtton的UIControlStateSelected屬性,來設定UIButton的選中背景圖檔。

- (UIButton *)normalButton
{
    if (!_normalButton)
    {
        UIImage *_ljImage = [UIImage imageNamed:@"lj_unselect.png"];
        _normalButton = [[UIButton alloc] initWithFrame:CGRectMake(kDEVICEWIDTH/2 - 80 - 40, 81 - 15, 50, 50)];
        //_normalButton.backgroundColor = [UIColor redColor];
        _normalButton.tag = 1000;
        [_normalButton setImage:[UIImage imageNamed:@"lj_unselect.png"] forState:UIControlStateNormal];
        [_normalButton setImage:[UIImage imageNamed:@"lj_select.png"] forState:UIControlStateSelected];
        [_normalButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_normalButton setSelected:YES]; //預設選中狀态
    }
    return _normalButton;
}

- (UIButton *)bigButton
{
    if (!_bigButton)
    {
        UIImage *_ljImage = [UIImage imageNamed:@"lj_unselect.png"];
        _bigButton = [[UIButton alloc] initWithFrame:CGRectMake(kDEVICEWIDTH/2 + 42 -10, 81 - 15, 50, 50)];
        //_bigButton.backgroundColor = [UIColor redColor];
        _bigButton.tag = 2000;
        [_bigButton setImage:[UIImage imageNamed:@"lj_unselect.png"] forState:UIControlStateNormal];
        [_bigButton setImage:[UIImage imageNamed:@"lj_select.png"] forState:UIControlStateSelected];
        [_bigButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bigButton;
}

/*
 字型選中按鈕點選
 */
- (void)buttonClick:(UIButton *)sender
{
    sender.selected = !sender.selected;//狀态取反
    if (sender.tag == 1000) //标準
    {
        [_bigButton setSelected:NO];
    }
    else if (sender.tag == 2000)//大
    {
        [_normalButton setSelected:NO];
    }
}

           

效果圖:

ios 巧用UIButton的UIControlStateSelected屬性

繼續閱讀