【问题标题】:Set gradient behind UITableView在 UITableView 后面设置渐变
【发布时间】:2015-05-03 18:56:04
【问题描述】:

我创建了一个 tableViewController 来调用这个函数:

func setTableViewBackgroundGradient(sender: UITableViewController ,let topColor:UIColor, let bottomColor:UIColor){

    let gradientBackgroundColors = [topColor.CGColor, bottomColor.CGColor]
    let gradientLocations = [0.0,1.0]

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientBackgroundColors
    gradientLayer.locations = gradientLocations

    gradientLayer.frame = sender.tableView.bounds
    sender.tableView.backgroundView?.layer.insertSublayer(gradientLayer, atIndex: 0)

}

与:

setTableViewBackgroundGradient(self, UIColor(0xF47434), UIColor(0xEE3965))

但我得到的只是:

【问题讨论】:

    标签: ios uitableview swift gradient


    【解决方案1】:

    您需要创建背景视图并将其分配给单元格:

    func setTableViewBackgroundGradient(sender: UITableViewController, _ topColor:UIColor, _ bottomColor:UIColor) {
    
        let gradientBackgroundColors = [topColor.CGColor, bottomColor.CGColor]
        let gradientLocations = [0.0,1.0]
    
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = gradientBackgroundColors
        gradientLayer.locations = gradientLocations
    
        gradientLayer.frame = sender.tableView.bounds
        let backgroundView = UIView(frame: sender.tableView.bounds)
        backgroundView.layer.insertSublayer(gradientLayer, atIndex: 0)
        sender.tableView.backgroundView = backgroundView
    }
    

    另外别忘了设置UITableViewCell背景色为清色:

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.backgroundColor = UIColor.clearColor()
    }
    

    【讨论】:

    • 单元格颜色也可以在storyboard中设置。
    • 如何添加单独的渐变背景?我的意思是,一个用于 tableview,另一个用于 tablecells?
    • 这将使大部分表格视图渐变不可见。但是你可以通过直接将渐变视图添加到单元格来达到相同的效果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    相关资源
    最近更新 更多