iOS在UIImageView顶部淡入黑色

Imr*_*ran 8 uiimageview ios cagradientlayer swift

我有一个UITableView在我的小区backgroundView是一个UIImageView.我希望每个图像的顶部都淡入黑色,这样我就可以覆盖一些白色文本.

我已经看过像一些答案这个,但没有一个似乎工作.

tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)我尝试过:

var imageView = UIImageView(image: image)

var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = imageView.frame
gradient.colors = [UIColor.blackColor(), UIColor.clearColor()]
gradient.locations = [0.0, 0.1]
imageView.layer.insertSublayer(gradient, atIndex: 0)

cell!.backgroundView = imageView
Run Code Online (Sandbox Code Playgroud)

但是,当我删除渐变代码时,我看不到渐变,也没有区别.我的渐变是否位于图像下方?

如果我替换线imageView.layer.insertSublayer(gradient, atIndex: 0),imageView.layer.mask = gradient那么我的细胞只是空白和白色(不再是图像).

lib*_*bec 9

gradient.colors你需要的数组中CGColor,所以:

gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor]
Run Code Online (Sandbox Code Playgroud)