iOS SDK:按标签编号设置按钮的背景颜色

时间:2012-07-17 14:51:46

标签: ios sdk

我有4个标签号为0,1,2,3的按钮。我想点击它时改变它的颜色。所以这就是我在做的事情:

switch ([sender tag]) {
        case 0:
                   [myButton0 setBackgroundColor:[UIColor redColor]];
                   break;
        case 1:
           [myButton1 setBackgroundColor:[UIColor redColor]];
                    break;
        case 2:
           [myButton2 setBackgroundColor:[UIColor redColor]];
            break;
        case 3:
                   [myButton3 setBackgroundColor:[UIColor redColor]];
           break;
}

我的问题是,如果有任何方法可以缩短代码,就像我们用标签号设置背景颜色一样?

谢谢

1 个答案:

答案 0 :(得分:1)

这就是我在做的事情。我已经在UIColor上为colorWithHexValue创建了一个类别。您可以使用您的代码。

 [signInButton setTitle:@"Sign In" forState:UIControlStateNormal];
signInButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
gradientLayer = [UIColor setGradientEffect:signInButton initialColor:0x797979 endColor:0x424242];
[[signInButton layer] insertSublayer:gradientLayer atIndex:0]; 
[signInButton setTitleColor:[UIColor colorWithHexValue:0xFFFFFF] forState:UIControlStateNormal];
[signInButton setTitleColor:[UIColor colorWithHexValue:0x000000] forState:UIControlStateSelected];

请使用

enum {
UIControlStateNormal       = 0,                       
UIControlStateHighlighted  = 1 << 0,                  // used when UIControl isHighlighted is set
UIControlStateDisabled     = 1 << 1,
UIControlStateSelected     = 1 << 2,                  // flag usable by app (see below)
UIControlStateApplication  = 0x00FF0000,              // additional flags available for application use
UIControlStateReserved     = 0xFF000000               // flags reserved for internal framework use

};