ios - 向 tableview 添加渐变会隐藏内容

标签 ios swift uitableview uiview cagradientlayer

我有一个 tableview,它运行良好。但我必须在背景上添加渐变。我在 viewDidLoad 中用这段代码做到了:

gradientLayer.frame = self.view.bounds
let color1 = UIColor.blueColor().CGColor as CGColorRef
let color2 = UIColor.redColor().CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 1, y: 0)
gradientLayer.endPoint = CGPoint(x: 0, y: 0)
self.view.layer.addSublayer(gradientLayer)
self.view.backgroundColor = UIColor.greenColor()

但现在我在 tableview 中看不到任何内容。

最佳答案

要适当配置背景渐变,您可以使用 UITableViewbackgroundView 属性和带有 CAGradientLayer 的 View 。生成的代码(在 Swift 3 中)将是:

/* A small UIView subclass displaying gradient */

class GradientView: UIView {

    /* Overriding default layer class to use CAGradientLayer */
    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }

    /* Handy accessor to avoid unnecessary casting */
    private var gradientLayer: CAGradientLayer {
        return layer as! CAGradientLayer
    }

    /* Public properties to manipulate colors */
    public var fromColor: UIColor = UIColor.red {
        didSet {
            var currentColors = gradientLayer.colors
            currentColors![0] = fromColor.cgColor
            gradientLayer.colors = currentColors
        }
    }

    public var toColor: UIColor = UIColor.blue {
        didSet {
            var currentColors = gradientLayer.colors
            currentColors![1] = toColor.cgColor
            gradientLayer.colors = currentColors
        }
    }

    /* Initializers overriding to have appropriately configured layer after creation */
    override init(frame: CGRect) {
        super.init(frame: frame)
        gradientLayer.colors = [fromColor.cgColor, toColor.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        gradientLayer.colors = [fromColor.cgColor, toColor.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
    }
}


/* Code that should be called in viewDidLoad method */

class MyViewController: UITableViewController {

    /* ... */

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.backgroundView = GradientView()
    }

    /* ... */

}

关于ios - 向 tableview 添加渐变会隐藏内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093439/

相关文章:

ios - Trigger.io 更新后“此平台不支持方法 API”

iOS - Crashlytics 缺少 dSYM 来处理崩溃

ios - 如何将项目排列成表格 View 中的部分?

swift - 如何在 UIView 中为 TableView 标题部分绘制自定义形状?

json - 如何实现 TableView 中显示的json的搜索操作

ios - Swift - 无法使用 AVPlayer 播放实时流视频

ios - iOS 8 iCloud Drive 是否支持不同用户共享文件?

ios - 在 "Charts by Daniel Cohen Gindi"的图表绘制自身之后,屏幕上的 UIButton 不再可选

swift - “Self”仅在协议(protocol)中或作为类方法的结果可用

ios - 删除行后,UITableView 不会更新