2015-05-03 12 views
9

tôi đã tạo ra một tableViewController nơi tôi gọi chức năng này:Set gradient UITableView

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) 

} 

với:

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

nhưng tất cả tôi nhận được là:

enter image description here

Trả lời

23

Bạn cần tạo chế độ xem nền và gán nó cho ô:

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 
} 

Cũng đừng quên để thiết lập màu nền UITableViewCell để xóa màu:

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

Yay, bạn đã lưu trong ngày của tôi, cảm ơn bạn rất nhiều! –

+0

giải pháp rất đẹp, cảm ơn bạn –

+0

màu ô cũng có thể được đặt trong bảng phân cảnh. –