开发者

Changing label color based on current label color in iPhone dev

I am having trouble figuring out the if statement code for changing the color of a UI label based on the current color of the label. For instance, if the label color is currently red and开发者_运维知识库 the correct button is pressed, I want the label color to change to black. If the label color is black I want the label color to change to blue.


In theory you could use a conditional like if ([label.backgroundColor isEqual:[UIColor blackColor]) { ... }, but you have to be careful because two colors that look the same may not necessarily pass isEqual:. (e.g. if one is grayscale and the other is 24 bit RGB).

Executing conditional logic based on visual attributes of your view seems like a design decision that you may want to reconsider anyway. You're making it more difficult to change your visual design in the future (for example, to use different colors) without introducing bugs in your application's logic. The Model View Controller pattern encourages us to decouple the state of our model, the logic that modifies it, and views that represent it visually. When your label cycles between three colors, the color presumably represents some underlying logical state that cycles between three possible values. A better choice would be to cycle that state within your underlying model, and let the label's color reflect that state.

For example, let's say your label's color represents a weapon selection in a rock, paper, scissors game:

// .h
typedef enum WeaponState {
    WeaponStateRock,
    WeaponStateScissors,
    WeaponStatePaper
} WeaponState;

// .m    
- (IBAction)weaponSelectorButtonClicked {
    if (weaponState == WeaponStateRock) {
        weaponState = WeaponStateScissors;
    }
    else if (weaponState == WeaponStateScissors) {
        weaponState = WeaponStatePaper;
    }
    else {
        weaponState = WeaponStateRock;
    }
    [self refreshView];
}

- (void)refreshView {
    if (weaponState == WeaponStateRock) {
        self.label.backgroundColor = [UIColor redColor];
    }
    else if (weaponState == WeaponStateScissors) {
        self.label.backgroundColor = [UIColor blackColor];
    }
    else {
        self.label.backgroundColor = [UIColor blueColor];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜