向UITableViewCell Swift添加渐变背景

Bri*_*den 1 iphone uitableview ios swift

我在这里发现了这个问题: Swift:在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)
  }
}
Run Code Online (Sandbox Code Playgroud)

显示的UITableViewCells是清晰的,因为我设置self.backgroundColorUIColor.clearColor().

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

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

self.backgroundView = UIView()
Run Code Online (Sandbox Code Playgroud)

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

Two*_*aws 11

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

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

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

@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]
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找更高级的功能,请尝试像SwiftyGradient这样的东西- 它做了很多相同的事情(UIView即将工作推进到使事情变得更容易),但具有更多功能.