2013-11-01 53 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"); 
}