0

我想以编程方式知道,我的 TextView 具有默认背景颜色或已更改。例如:

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

我有一个想法:

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

但我觉得不太对。有人有更好的想法吗?

4

6 回答 6

5

尝试这个 -

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

if(color1 == color2) {
    NSLog(@"Default");
} else {
     NSLog(@"Changed");
}
于 2013-11-01T12:34:35.857 回答
3

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

于 2013-11-01T12:15:51.553 回答
1

该属性backgroundColor返回一个UIColor具有背景颜色的对象。只需将其与另一个 UIColor 进行比较。

只要etalon.backgroundColordefaultColor是,您的两个选项似乎都是正确的UIColor

于 2013-11-01T11:55:26.850 回答
0

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

这里有一些文档可以帮助您开始使用 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];
    }
}
于 2013-11-01T12:05:12.307 回答
0

像这样检查:

   if (myTextView.backgroundColor == [UIColor clearColor])
   {
       // your code here
   }
于 2013-11-01T12:12:06.177 回答
0

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

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

请参阅如何比较 UIColors中的 samvermette 的回答?对于 的定义isEqualToColor

于 2013-11-01T12:20:21.870 回答