Obj-C-用自定义int值编程设置图像视图背景颜色



我试图用从另一个ViewController(self.receivedData.text(传递的字符串中的整数来设置我的imageview的背景色。我使用以下代码来分隔字符串中的值;返回的字符串(例如(为:100、210、70,然后分解为一个数组。然而,这一切都有效:

a(我只能访问分隔字符串中的第一个值(数组;试图访问其他两个值会使我的应用程序崩溃,即使它们存在(和

b(当我尝试将这些值设置为适当的绿色:蓝色:和红色:值时,我的图像视图保持为空?

我该怎么解决这个问题?

ViewController.m

NSArray *array = [self.receivedData.text componentsSeparatedByString:@","];
NSLog(@"Show the count %lu", (unsigned long)[array count]);

for (NSUInteger i=1; i< array.count; i++) {

NSString *comp1 = array[0];
NSString *comp2 = array[1];
NSString *comp3 = array[2];

NSInteger red = [comp1 integerValue];
NSLog(@"What is comp1 %ld", red);
NSInteger green = [comp2 integerValue];
NSLog(@"What is comp2 %ld", green);
NSInteger blue = [comp3 integerValue];
NSLog(@"What is comp3 %ld", blue);

NSLog(@"In the array you will find %@", array);

[self.colorSwatch setBackgroundColor:[UIColor colorWithRed:red green:green blue:blue alpha:1.0]];


NSLog(@"content @%",array[i]);
}

非常确定您正在崩溃,因为

NSLog(@"content %@", array[i]);

至少在最后一个循环中超过了预期的最大索引3,索引为4。

您还可以根据数组中的索引数量在for循环中直接访问索引。所以你实际上做了3次同样的事情。

相反,它可以这样写…

NSString *text = @"100, 210, 70,";
NSArray *array = [text componentsSeparatedByString:@","];
//NSArray *shouldResultIn = @[@"100",@" 210",@" 70",@""];

所以你要确保你永远不会访问高于array.count的索引,但要确保你至少有索引0,1,2可用的

if (array.count>2) {

CGFloat colorFactor = 1.0f/256.0f;
CGFloat r = colorFactor * (CGFloat)[(NSString *)array[0] integerValue];
CGFloat g = colorFactor * (CGFloat)[(NSString *)array[1] integerValue];
CGFloat b = colorFactor * (CGFloat)[(NSString *)array[2] integerValue];
// why multiplication? 
// because you don't want devision by 0 -> error.

UIColor *bgColor = [UIColor colorWithRed:r green:g blue:b alpha:1.0];

[self.colorSwatch setBackgroundColor:bgColor];
NSLog(@"color %f %f %f",r, g, b);
if (array.count>3) NSLog(@"not used separatedString in array %@",array[3]);
}

你也可以写

if (array.count==3) { ... }

以确保只有在恰好有3个索引的情况下才处理它。

但是对于字符串中的字母来说,这仍然不安全。认为您已经在self.receivedData.text的输入法中确保了这一点

此外,UIColor-colorWithRed:green:blue:alpha:需要CGFloat参数,此处不适合转换为NSInteger。如果你的整数定义为每个色调最多256种颜色,那么一个小辅助公式会有所帮助。

最新更新