美好的一天!我只想问一下如何根据输入的数字改变UILabel的背景颜色?例如,如果数字为0则为蓝色,如果数字为1-2则变为绿色。如果数字是3-4,它将变为橙色。谢谢你的答案!
答案 0 :(得分:3)
你可以像这样设置......
int number = [yourLbl.text intValue];
if(number == 0)
yourLbl.backgroundColor = [UIColor blueColor];
else if(number == 1 || number == 2)
yourLbl.backgroundColor = [UIColor greenColor];
else if(number == 3 || number == 4)
yourLbl.backgroundColor = [UIColor orangeColor];
else
yourLbl.backgroundColor = [UIColor redColor];
答案 1 :(得分:2)
UITextFieldDelegate
没有didChange方法。您必须手动添加行为。您可以使用shouldChangeCharactersInRange:
方法,但我个人建议您不要覆盖方法,除非您绝对不得不这样做。
[yourTextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
然后,在目标方法中,将背景颜色设置为:
- (void)textFieldDidChange{
if ([yourTextField.text isEqualToString:@"1"] || [yourTextField.text isEqualToString:@"2"])
yourLabel.backgroundColor = [UIColor blueColor];
else if (...)
.
.
//and so on
}
答案 2 :(得分:0)
您无法在UILabel上输入,请使用UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
int number = [textField.text intValue];
if(number == 0) {
label.backgroundColor = [UIColor blueColor];
} else if(number == 1 || number == 2) {
label.backgroundColor = [UIColor greenColor];
} else if(number == 3 || number == 4)
label.backgroundColor = [UIColor orangeColor];
}
return YES;
}
答案 3 :(得分:0)
首先将标签文本编号转换为 int ,而不是使用 backgroundColor 作为标签背景。
int number = [yourLabel.text intValue];
if(number == 0)
yourLabel.backgroundColor = [UIColor blueColor];
else if(number == 1 || number == 2)
yourLabel.backgroundColor = [UIColor greenColor];
else if(number == 3 || number == 4)
yourLabel.backgroundColor = [UIColor orangeColor];
else
yourLabel.backgroundColor = [UIColor grayColor];
答案 4 :(得分:-1)
在textfielddidendediting中尝试此条件
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if(label.text isEqualToString:0)
{
label.backgroundColor=[UIColor blueColor];
}
else
{
label.backgroundColor=[UIColor blueColor];
}
}