如何检查UIButton的背景颜色

时间:2014-11-20 12:32:25

标签: ios objective-c xcode

有没有办法检查UIButton的背景。

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
btn.backgroundColor = [UIColor blueColor];
[self.view addSubview:btn];

现在我想检查我的按钮是否具有backgroundcolor。

6 个答案:

答案 0 :(得分:3)

我认为您提出这个问题是因为您没有看到任何结果/没有看到任何按钮。 你以错误的方式启动按钮,你应该这样做:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(50, 50, 300, 100)];
[button setBackgroundColor:[UIColor blueColor]];
NSLog(@"%@", button.backgroundColor);
[self.view addSubview:button];

我还添加了NSLog(),以便您检查背景颜色。

2014-11-20 13:35:14.438 App[19290:3475731] UIDeviceRGBColorSpace 0 0 1 1

您将获得一个UIDeviceRGBColorSpace和一些数字,代表:

RED GREEN BLUE ALPHA

答案 1 :(得分:1)

您可以使用以下代码检查您的按钮是否具有背景颜色。 isEqual将匹配两个对象是否相同。

if ([btn.backgroundColor isEqual:[UIColor colorWithRed:74.0f/255.0f green:165.0f/255.0f blue:155.0f/255.0f alpha:1]])
    NSLog(@"Same color");
else
    NSLog(@"not same");

如果你更改rgb,那么你将会变得不一样。

答案 2 :(得分:0)

试试这个:

if (btn.backgroundColor == [UIColor blueColor]) {
   NSLog(@"My button background is blue");
}

答案 3 :(得分:0)

我想你只想得到UIButton的背景色

UIColor* buttonColor = button.backgroundColor;

试试这个,让我知道。

答案 4 :(得分:0)

如果我的问题正确,您只想获得按钮的背景色?

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
btn.backgroundColor = [UIColor blueColor];

if (btn.backgroundColor==nil)
NSLog(@"no bg set");
else
NSLog(@"%@",btn.backgroundColor);

答案 5 :(得分:0)

UILabel *lblHeader = [[UILabel alloc]initWithFrame:CGRectMake(5, 15, self.view.frame.size.width-10, 44)];
lblHeader.backgroundColor = [UIColor blueColor]; 
lblHeader.text = [arrImages objectAtIndex:indexPath];
lblHeader.textColor = [UIColor whiteColor];
NSLog(@"color of lable is %@",lblHeader.backgroundColor);
[self.view addSubview:lblHeader];

然后输出您的背景颜色您可以在控制台中看到: -

2014-11-20 18:51:29.067 iSeventhAssignment [2500:103851] 标签的颜色是UIDeviceRGBColorSpace 0 0 1 1