向UITableViewCell Swift添加渐变背景

时间:2015-12-17 17:41:49

标签: ios iphone swift uitableview

我在这里发现了这个问题: Swift: gradient on a cell of a tableview

我正在使用Custom UITableViewCell,其中包含以下代码:

public class MyCustomUITableViewCell: UITableViewCell {
 override public func layoutSubviews() {
    super.layoutSubviews()

    //setting backgroundColor works
    //self.backgroundColor = UIColor.brownColor()

    self.backgroundColor = UIColor.clearColor()

    let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0).CGColor
    let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0).CGColor

    let gradient = CAGradientLayer()
    gradient.colors = [ colorTop, colorBottom]
    gradient.locations = [ 0.0, 1.0]

    self.backgroundView = UIView()

    //setting view backgroundColor does not work
    //self.backgroundView?.backgroundColor = UIColor.redColor()

    self.backgroundView!.layer.insertSublayer(gradient, atIndex: 0)
  }
}

显示的UITableViewCells清晰,因为我将self.backgroundColor设置为UIColor.clearColor()

渐变没有显示,如果不是向UITableViewCell.backgroundView添加渐变,我只是将UITablveViewCell.backgroundView.backgroundColor设置为UIColor.redColor(),这也不起作用。

当我在这行代码中创建UITableViewCell.backgroundView时:

self.backgroundView = UIView()

我假设backgroundView会自动填充UITableView中显示的UITableViewCells的边界,换句话说,backgroundView不是0x0宽度x高度正确吗?

2 个答案:

答案 0 :(得分:10)

这可能对你和其他人有所帮助:它是我用来绘制渐变的(微小)UIView子类,而不必陷入插入CALayers的混乱中。这种方式UIView使用自动布局等方式处理大小调整,这样更容易使用。

将此代码放入项目中的文件中,然后将其用作普通视图。如果需要,它可以直接进入单元格的背景视图。如果以这种方式使用,您应该能够自定义代码或IB中的颜色。

这是一个微不足道的代码,但请考虑CC-0 licensed - 即尽可能使用公共域名,“只要你想要”使用它“其他地方。

@IBDesignable class GradientView: UIView {
    @IBInspectable var firstColor: UIColor = UIColor.whiteColor()
    @IBInspectable var secondColor: UIColor = UIColor.blackColor()

    override class func layerClass() -> AnyClass {
        return CAGradientLayer.self
    }

    override func layoutSubviews() {
        (layer as! CAGradientLayer).colors = [firstColor.CGColor, secondColor.CGColor]
    }
}

如果您正在寻找更高级的功能,请尝试类似SwiftyGradient的内容 - 它可以做同样的事情(即将工作推送到UIView以简化操作),但具有更多功能

答案 1 :(得分:3)

正如UITableViewCell的文档中所述:

  

如果要更改单元格的背景颜色,请执行此操作   tableView:willDisplayCell:forRowAtIndexPath:表视图的方法   委派。

我通常只是将另一个视图添加到我用作背景视图的单元格中,该视图适用于所有情况。

相关问题