我正在尝试根据我找到的代码 on this blog. 使用渐变自定义分组 UITableViewCell 的 backgroundView
它是 UIView 的子类,用于 cell.backgroundView。
背景渐变的颜色在原始代码中是这样定义的:
#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);
我正在尝试实现一个函数来设置渐变的开始和结束颜色,该函数需要两个 UIColor,然后填充全局 float 组 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
,但我很快就没有想法了。
我根本不明白,为什么我不能用这种方式填充我的 float 组?我做错了什么?
最佳答案
评论添加为答案:
以这种方式创建数组的唯一方法是在代码中动态创建。如果要添加到 iVar(类变量),则需要一一进行,因为内存已在初始化时分配。因此使用 startAndEndColors[0] = ...
等。
至于您的后续问题:不,没有办法以这种方式将值分配给已经在分配阶段初始化的内存。如果您使用 std::vector 或其他对象,那么这是可能的。
解决这个问题的方法是在标题中添加类似的内容
CGFloat *startAndEndColors;
然后在您的实现中执行类似的操作
float colorsTest[8] = {red, green, blue, alpha, red1, green1, blue1, alpha1};
startAndEndColors = colorsTest;
这样您就可以按照您想要的方式初始化它,但无法保证 startAndEndColors
对象中的对象数量。如果您尝试访问其边界之外的内容,您稍后可能会将其分配给错误大小的内容并导致崩溃。
关于ios - 将 float 分配到全局数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17595011/