gpt4 book ai didi

objective-c - 将 NSString 转换为 UIColor

转载 作者:行者123 更新时间:2023-12-03 07:09:56 27 4
gpt4 key购买 nike

我有一个充满 NSString 的数组,我需要使用 NSString 来更改属性文本的颜色。我将原始 NSString 分成一个包含单个 NSString 和颜色的数组,但我被困在这里。数组中的字符串是 [UIColor Orangecolor]。我已经尝试过,但它返回 null。

 SEL blackSel = NSSelectorFromString(@"blackColor");
UIColor* tColor = nil;
if ([UIColor respondsToSelector: blackSel])
tColor = [UIColor performSelector:blackSel];

最佳答案

我编写了一个自定义的 NSValueTransformer 来允许我将 NSColor 转换为 NSString(并返回)以存储到 NSUserDefaults 因为我不喜欢使用字节数组存储颜色,这是默认行为。如果您在 IB 中设置自定义变压器,它也可以跨 KVO 使用。当然,您也可以在代码中调用静态方法来执行转换。

针对 UIColor 进行修改应该不会花费很多工作:

StringColourTransformer.h:

#import <Cocoa/Cocoa.h>

@interface StringColourTransformer : NSValueTransformer

+ (NSString *)toString:(NSColor *)value;
+ (NSColor *)fromString:(NSString *)value;

@end

StringColourTransformer.m:

#import "StringColourTransformer.h"

@implementation StringColourTransformer

+ (NSString *)toString:(NSColor *)value
{
StringColourTransformer *transformer = [[StringColourTransformer alloc] init];
NSString *str = [transformer reverseTransformedValue:value];
return str;
}

+ (NSColor *)fromString:(NSString *)value
{
StringColourTransformer *transformer = [[StringColourTransformer alloc] init];
NSColor *color = (NSColor *)[transformer transformedValue:value];
return color;
}

+ (Class)transformedValueClass
{
return [NSString class];
}

+ (BOOL)allowReverseTransformation
{
return YES;
}

- (id)transformedValue:(id)value
{
CGFloat r = 0.0, g = 0.0, b = 0.0, a = 1.0;

// Only NSString classes are reverse-transformed
if ([value isKindOfClass:[NSString class]])
{
NSString *stringValue = (NSString *)value;
sscanf([stringValue UTF8String],
#ifdef __x86_64
"%lf %lf %lf %lf",
#else
"%f %f %f %f",
#endif
&r, &g, &b, &a);
}

return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:a];
}

- (id)reverseTransformedValue:(id)value
{
CGFloat r = 0.0, g = 0.0, b = 0.0, a = 1.0;

// Only NSColor classes are transformed
if ([value isKindOfClass:[NSColor class]])
{
NSColor *colourValue = (NSColor *)value;
NSColor *converted = [colourValue colorUsingColorSpaceName:@"NSCalibratedRGBColorSpace"];
[converted getRed:&r green:&g blue:&b alpha:&a];
}

return [NSString stringWithFormat:@"%.3f %.3f %.3f %.3f", r, g, b, a];
}

@end

关于objective-c - 将 NSString 转换为 UIColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17121327/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com