【问题标题】:IOS Gradient overlay become solid color after scrollingIOS渐变叠加滚动后变成纯色
【发布时间】:2013-03-06 07:29:34
【问题描述】:

我有一个自定义的表格视图,它将填充动态对象以形成一个列表。我正在尝试在单元格中图像的一半顶部设置渐变叠加。

我在 interface.builder 中设置了布局。

以下是我的问题: - 我遇到的问题是我的渐变叠加层似乎每次都会重新绘制,导致它在向上/向下滚动后变成纯色叠加层。有人知道如何克服这个问题吗?

谢谢!


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CustomTableViewCell *cell = (CustomTableViewCell* )[tableView dequeueReusableCellWithIdentifier:@"TableCellId"];
    if(cell == nil){
        cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TableCellId"];
    }

    UIImageView *item_image = (UIImageView *)[cell viewWithTag:@"cell_image"];
    NSString *url_image = [NSString stringWithFormat:@"%@%@", URL_SERVER_HOST, item_pic];

    [item_image setImageWithURL:[NSURL URLWithString:url_image]];

    //Currently get called when new cell is loaded
    UIView *overlay = (UIView *)[cell viewWithTag:@"cell_overlay"];
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = overlay.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
    [overlay.layer insertSublayer:gradient atIndex:0];

    UILabel * item_name = (UILabel *)[cell viewWithTag:@"cell_name"];
    item_name.text  = @"test text";

    return cell;
}

【问题讨论】:

    标签: ios


    【解决方案1】:

    将渐变相关的代码放到if (cell == nil)中,这样单元格被复用的时候就不会再添加渐变层了

    【讨论】:

    • 我试过了,但不知何故单元格永远不会为零,移动它会导致梯度永远不会被调用
    • 如果使用storyboard创建cell或者将nib注册到tableview中,可以在cell的class中-awakeFromNib方法中添加渐变层。否则你可以在 -initWithStyle:reuseIdentifier 中添加渐变层。
    【解决方案2】:

    我只是在应用渐变之前将叠加子层设置为 nil。只需在[overlay.layer insertSublayer:gradient atIndex:0];之前写下一行

    overlay.layer.sublayers = nil;

    【讨论】:

      猜你喜欢
      • 2016-06-18
      • 2013-07-29
      • 2023-03-10
      • 2020-03-08
      • 2016-04-18
      • 2016-12-02
      • 1970-01-01
      • 2013-03-22
      • 2014-10-17
      相关资源
      最近更新 更多