2015年9月28日 星期一

用 UIButton 製作開關掣


今日嘗試利用 UIButton 製作成只有「開」及「關」兩個狀態的按鈕。原來不容易,花的時間比預計的多。

不解釋,直接來代碼:
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTag:i];
[button setFrame:rect];
[button setBackgroundColor:[UIColor redColor]];
[button setTitle:string forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button.titleLabel setFont:fontTag];
[button.layer setCornerRadius:(rect.size.height*0.5f)];
[button addTarget:self action:@selector(changeSubCategory:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
- (void)changeSubCategory:(UIButton *)button  {
    button.selected = !button.selected;
    if (button.selected == NO)  {
        [button setBackgroundColor:[UIColor darkGrayColor]];
    }  else  {
        [button setBackgroundColor:[UIColor redColor]];
    }

    //  Do some more things...
}

沒有留言: