与TableView的渐变

时间:2017-09-11 09:02:42

标签: ios swift uitableview gradient

我为tableView做了一个渐变,一切正常,但是当我向上滚动时,会出现一个黑色空格,我该如何解决呢?我知道这是因为我做了一个透明{ {1}} 即可。 有可能并且在objective-c

tableView

2 个答案:

答案 0 :(得分:1)

我建议将渐变应用于位于TableView后面的另一个UIView。这可能是ViewControllers视图,或者只是一个新的UIView。然后,您只需确保调整UIView的大小以匹配表。

答案 1 :(得分:1)

问题是您正在更改表视图的图层,您应该更改父视图控制器的图层,以便:

    //change
    gradient.frame = self.tableView.bounds 
    //to
    gradient.frame = self.view.bounds

    //and change
    tableView.layer.insertSublayer(gradient, at: 0) 
    //to
    self.view.layer.insertSublayer(gradient, at: 0)

完整代码看起来像这样:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CAAnimationDelegate {

let arr = ["ddd", "sss", "rrr","ddd", "sss", "rrr","ddd", "sss", "rrr","ddd", "sss", "rrr"]

@IBOutlet weak var tableView: UITableView!

let gradient = CAGradientLayer()
var gradientSet = [[CGColor]]()
var currentGradient: Int = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    tableView.delegate = self
    tableView.dataSource = self
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    gradientSet.append([UIColor.blue.cgColor , UIColor.red.cgColor])
    gradientSet.append([UIColor.brown.cgColor, UIColor.orange.cgColor])
    gradientSet.append([UIColor.yellow.cgColor, UIColor.gray.cgColor])



    gradient.frame = self.view.bounds
    gradient.colors = gradientSet[currentGradient]
    gradient.startPoint = CGPoint(x:0, y:0)
    gradient.endPoint = CGPoint(x:1, y:1)
    gradient.drawsAsynchronously = true
    self.view.layer.insertSublayer(gradient, at: 0)

    animateGradient()

}

func animateGradient() {
    if currentGradient < gradientSet.count - 1 {
        currentGradient += 1
    } else {
        currentGradient = 0
    }

    let gradientChangeAnimation = CABasicAnimation(keyPath: "colors")
    gradientChangeAnimation.delegate = self
    gradientChangeAnimation.duration = 5.0
    gradientChangeAnimation.toValue = gradientSet[currentGradient]
    gradientChangeAnimation.fillMode = kCAFillModeForwards
    gradientChangeAnimation.isRemovedOnCompletion = false
    gradient.add(gradientChangeAnimation, forKey: "colorChange")
}




func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    if flag {
        gradient.colors = gradientSet[currentGradient]
        animateGradient()
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = arr[indexPath.row]
    cell.backgroundColor = UIColor.clear
    return cell
}}

在: image_before

在: image_after

相关问题