默认是backgroundColor吗?

时间:2013-11-01 11:50:24

标签: ios objective-c

我想以编程方式知道,我的TextView有默认的backgroundColor或更改。 例如:

if (myTextView.backgroundColor == defaultColor){
NSLog(@"default");
} else {
NSLog(@"changed");
}

我有一个想法:

UITextView *etalon = [UITextVew new];
if (myTextView.backgroundColor == etalon.backgroundColor){
NSLog(@"default");
} else {
NSLog(@"changed");
}

但我认为这不太对。 有人有更好的想法吗?

6 个答案:

答案 0 :(得分:5)

试试这个 -

const float* color1 = CGColorGetComponents(myTextView.backgroundColor.CGColor);
const float* color2 = CGColorGetComponents(etalon.backgroundColor.CGColor);

if(color1 == color2) {
    NSLog(@"Default");
} else {
     NSLog(@"Changed");
}

答案 1 :(得分:3)

您应该使用[myTextView.backgroundColor isEqual:etalon.backgroundColor]进行颜色比较。另外要小心,因为不同的颜色空间会给你一个不等于的结果。

答案 2 :(得分:1)

属性backgroundColor返回一个UIColor对象,其背景颜色为。只需将它与另一个UIColor进行比较。

只要etalon.backgroundColordefaultColorUIColor,您的两个选项都是正确的。

答案 3 :(得分:0)

我不知道您的问题的背景(即您想要做什么),但您的问题的另一种方法可能涉及使用键值观察来观察文本视图背景颜色的变化,并采取相应的行动。

Here's some documentation让您开始使用KVO。

在代码中:

static void * kBackgroundColorCtx = &kBackgroundColorCtx;

[self.myTextView addObserver:self
                 forKeyPath:@"backgroundColor"
                    options:NSKeyValueObservingOptionOld
                    context:kBackgroundColorCtx];

然后,在您的视图控制器中实现:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kBackgroundColorCtx) {
        NSLog(@"Background color changed from %@ to %@", 
              [change objectForKey:NSKeyValueChangeOldKey],
              self.myTextView.backgroundColor);
    } else {
        // Not interested in this, pass to superclass
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

答案 4 :(得分:0)

像这样检查:

   if (myTextView.backgroundColor == [UIColor clearColor])
   {
       // your code here
   }

答案 5 :(得分:0)

如何使用外观代理获取默认值:

UITextView *appearanceProxy = (UITextView *)[UITextView appearance];
if ([myTextView.backgroundColor isEqualToColor:appearanceProxy.backgroundColor]){
    NSLog(@"default");
} else {
    NSLog(@"changed");
}

有关isEqualToColor的定义,请参阅samvermette在How to compare UIColors?的回答。