【问题标题】:Assigning of floats into global array将浮点数分配到全局数组中
【发布时间】:2013-07-11 13:42:13
【问题描述】:

我正在尝试使用渐变自定义分组 UITableViewCell 的 backgroundView,基于我找到的代码 on this blog. 它是用于 cell.backgroundView 的 UIView 的子类。

背景渐变的颜色在原代码中是这样定义的:

#define TABLE_CELL_BACKGROUND    { 1, 1, 1, 1, 0.866, 0.866, 0.866, 1}          // #FFFFFF and #DDDDDD

然后,在子类 backgroundView 的drawRect 上像这样使用:

CGFloat components[8] = TABLE_CELL_BACKGROUND;
myGradient = CGGradientCreateWithColorComponents(myColorspace, components , locations, 2);

我正在尝试实现一个函数来设置渐变的开始和结束颜色,它需要两个 UIColors,然后填充一个全局浮点数组 float startAndEndColors[8](在 .h / @interface 中)以供以后使用:

-(void)setColorsFrom:(UIColor*)start to:(UIColor*)end{

    float red = 0.0, green = 0.0, blue = 0.0, alpha =0.0, red1 = 0.0, green1 = 0.0, blue1 = 0.0, alpha1 =0.0;

    [start getRed:&red green:&green blue:&blue alpha:&alpha];
    [end getRed:&red1 green:&green1 blue:&blue1 alpha:&alpha1];

    //This line works fine, my array is successfully filled, just for test
    float colorsTest[8] = {red, green, blue, alpha, red1, green1, blue1, alpha1};

    //But for this one, I just have an error.
    //"Expected expression"
    //                 \
    //                  v
    startAndEndColors = {red, green, blue, alpha, red1, green1, blue1, alpha1};
}

但它在分配时向我抛出了这个错误“预期表达式”。

我尝试使用CGFloat,拼命添加随机const,但我很快就没有想法了。

我只是不明白,为什么我不能用这种方式填充我的浮点数组?我做错了什么?

【问题讨论】:

  • 以这种方式创建数组的唯一方法是在代码中动态创建。如果要添加到 iVar(类变量),则需要一一进行,因为在初始化时已经分配了内存。所以使用startAndEndColors[0] = ...
  • 成功了,谢谢!但是有没有办法像我对colorsTest所做的那样添加所有这些值?请将您的评论切换为答案,我会接受。

标签: ios objective-c arrays uitableview cgfloat


【解决方案1】:

评论添加为答案:

以这种方式创建数组的唯一方法是在代码中动态创建。如果要添加到 iVar(类变量),则需要一一进行,因为在初始化时已经分配了内存。所以使用startAndEndColors[0] = ...等。

至于您的后续问题:不,没有办法以这种方式将值分配给已在分配阶段初始化的内存。如果您使用 std::vector 或其他对象,那将是可能的。

在你的标题中可以这样解决问题

CGFloat *startAndEndColors;

然后在你的实现中像这样

float colorsTest[8] = {red, green, blue, alpha, red1, green1, blue1, alpha1};
startAndEndColors = colorsTest;

这样你可以按照你想要的方式初始化它,但是你不能保证startAndEndColors对象中的对象数量。如果您尝试访问超出其范围的内容,您以后可能会将其分配给错误大小的内容并导致崩溃。

【讨论】:

  • 确实,您的第二个提议似乎奏效了。此外,当startAndEndColorsCGFloat * 时,可以直接分配startAndEndColors = (float[]){red,green,blue,alpha,red1,green1,blue1,alpha1}
猜你喜欢
  • 2015-07-21
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多