CAGradientLayer没有显示?

时间:2016-07-22 13:05:20

标签: ios swift cagradientlayer

好的,我有一个集合视图和我使用Xib文件创建的自定义单元格,以便我可以在另一个集合视图中使用相同的单元格在不同的视图上。在我的cellForItemAtIndexPath中我有:

let cell = collectionView.dequeueReusableCellWithReuseIdenitifier(cellIdentifier, forIndexPath: indexPath) as! StoriesCollectionViewCell
cell.setCell(arrArticles[indexPath.item])

return cell

并在setCell func中的自定义单元格类中:

func setCell(article : Article) {
    self.articleImageView.alpha = 0.0
    self.storyHeadline.text = article.headline

    //set the background for the txtView to a gradient, from clear to white
    let gradient = CAGradientLayer()
    gradient.frame = txtView.frame
    gradient.colors = [UIColor.clearColor().CGColor, UIColor.whiteColor().CGColor]
//        gradient.startPoint = txtView.frame.origin
//        gradient.endPoint = CGPointMake(txtView.frame.maxX, txtView.frame.maxY)
    self.txtView.layer.insertSublayer(gradient, atIndex: 0)

    //for testing purpose only, will be replaced by web service response
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = .MediumStyle
    dateFormatter.timeStyle = .NoStyle

    self.storyHeadlineDate.text = dateFormatter.stringFromDate(article.date!)
    manager.imageForArticle(article) { (image) in
        self.articleImageView.image = image
        UIView.animateWithDuration(1, animations: {
            self.articleImageView.alpha = 1.0
        })
    }
    self.layer.cornerRadius = 5.0
}

一切都像我想要的那样工作,而不是渐变背景颜色。我还想知道是否有更好的委托方法来设置这个渐变.txtView是一个从xib,btw创建和链接的UIView。

1 个答案:

答案 0 :(得分:0)

尝试将此代码写入tableViewCell文件

override func didMoveToSuperview() {

    let screenWidth = UIScreen.mainScreen().bounds.width
    gradientView.bounds.size.width = screenWidth
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = gradientView.bounds
    gradient.colors = [
        UIColor(hex: "#030303" ,alpha: 0).CGColor,
        UIColor(hex: "#030303"  ,alpha: 0.6).CGColor ]
    print("color set: ", gradient.colors)
    gradient.locations = [0.0, 0.6]
    gradient.opacity = 0.4

    gradientView.layer.insertSublayer(gradient, atIndex: 0)
    gradientView.layer.masksToBounds = true

}