gpt4 book ai didi

ios - 向 UITableViewCell Swift 添加渐变背景

转载 作者:搜寻专家 更新时间:2023-11-01 05:45:54 25 4
gpt4 key购买 nike

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

我正在使用具有以下代码的自定义 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 高吗?

最佳答案

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

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

这是微不足道的代码,但请考虑一下 CC-0 licensed – 即尽可能使用公共(public)领域,“随心所欲地使用它”。

@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 以使事情变得更容易),但具有更多功能。

关于ios - 向 UITableViewCell Swift 添加渐变背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com