2013-11-01 51 views
0

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

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

我有一个想法:

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

但我认为这是不完全正确。 任何人有更好的想法?

+1

出于好奇,为什么你想知道吗? –

回答

1

财产backgroundColor返回一个UIColor对象,与您背景的颜色。只需将它与另一个UIColor进行比较即可。

你的两个选择似乎都对,只要etalon.backgroundColordefaultColorUIColor

0

我不知道你的问题的背景(即你想做什么),但另一种解决问题的方法可能涉及使用Key Value Observing观察文本视图背景颜色的变化,并据此采取行动。

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]; 
    } 
} 
0

检查这样的:

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

Textview的默认颜色是白色,所以使用清晰的颜色api。 –

3

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

0

如何使用外观代理抢默认:

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

见samvermette的回答在How to compare UIColors?isEqualToColor定义。

5

试试这个 -

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

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