ios - 什么时候是将 CALayers/CAGradientLayers 添加到 iOS 8.3 的 UITableViewCells 或 UICollectionViewCells 的最佳方式?

标签 ios objective-c calayer cagradientlayer

我创建了一个类方法来创建一个可以添加到我想要的任何 View 的渐变层。

+ (CAGradientLayer *)createPartialGradientWithFrame:(CGRect)frame
{
    UIColor *color1 = [[UIColor blackColor] colorWithAlphaComponent:0.00f];
    UIColor *color2 = [[UIColor blackColor] colorWithAlphaComponent:0.10f];
    UIColor *color3 = [[UIColor blackColor] colorWithAlphaComponent:0.25f];
    UIColor *color4 = [[UIColor blackColor] colorWithAlphaComponent:0.50f];
    UIColor *color5 = [[UIColor blackColor] colorWithAlphaComponent:0.75f];

    NSArray *colors = @[(id)color1.CGColor,
                        (id)color2.CGColor,
                        (id)color3.CGColor,
                        (id)color4.CGColor,
                        (id)color5.CGColor];

    NSNumber *stop1 = [NSNumber numberWithFloat:0.00f];
    NSNumber *stop2 = [NSNumber numberWithFloat:0.25f];
    NSNumber *stop3 = [NSNumber numberWithFloat:0.50f];
    NSNumber *stop4 = [NSNumber numberWithFloat:0.75f];
    NSNumber *stop5 = [NSNumber numberWithFloat:1.00f];

    NSArray *locations = @[stop1, stop2, stop3, stop4, stop5];

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = colors;
    gradientLayer.locations = locations;
    gradientLayer.frame = frame;

    return gradientLayer;
}

我想将它用作表格 View 或 Collection View 中我的单元格的背景层。

如果我只是在初始化期间添加它,如果 View Controller 使用自动布局,框架将是错误的。

我还尝试在单元格子类中使用此代码:

- (void)layoutSubviews {
    [super layoutSubviews];
    aGradientLayer.frame = self.contentView.bounds;
}

它有时可以工作,但对于 iOS 8.3,当 View 出现时,框架仍然不合适。

编辑:更新的代码片段。

最佳答案

几个选项:

  1. 在“init”方法(或 init 的任何其他扩展)和“layoutSubviews”方法中初始化,调整其大小,但务必调用 [super layoutSubviews]!

  2. 使用 [UIScreen mainScreen].bounds 和一些数学计算单元格的宽度/高度。

我会选择第 1 条。如果您不调用 [super layoutSubviews],contentView 可能无法正确调整大小。

关于ios - 什么时候是将 CALayers/CAGradientLayers 添加到 iOS 8.3 的 UITableViewCells 或 UICollectionViewCells 的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657150/

相关文章:

iOS 键盘扩展以 "per-process-limit"终止

iphone - 无法使用 CALayer for iphone 创建 ken burns 效果

移动开发用Android还是iOS?

ios - 更新和编辑 CoreData 中的实体

iphone - 无法在 iPhone 设备中运行应用程序

ios - Objective-C 函数通过在方法签名中指定关系来更新 Core Data 关系

objective-c - 如何让 imageview 做一个 segue

ios - Size 类下的 AVCaptureVideoPreviewLayer 自动旋转

ios - 如何在 swift 中为 CAReplicatorLayer 的更新位置设置动画?

ios - 为 iOS arm64 编译的 G729 编解码器无法正常运行