簡體   English   中英

自定義UITableViewCell中的UIView在滾動時重繪

[英]UIView in custom UITableViewCell redraws when scrolling

我在自定義UITableView添加了一個UIView以像可用性欄一樣或多或少地繪制。 我有兩個問題:

1.-僅當新單元格出現在屏幕上而不是啟動時才繪制視圖,如下面的GIF所示。

2.-滾動tableView幾次時,每個單元格上的UIView被重繪,因此它們彼此重疊

GIF

UITableViewCell的代碼:

import UIKit

class CustomTableViewcell: UITableViewCell {

    @IBOutlet weak var bikeStationLabel: UILabel!
    @IBOutlet weak var progressView: UIView!
    @IBOutlet weak var distanceLabel: UILabel!


    override internal func awakeFromNib() {

    }
}

我認為那里沒有錯,很簡單。 我認為我的問題來自func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell方法。 到目前為止,我有:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: CustomTableViewcell! = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewcell
    cell.backgroundColor = UIColor(red: 120/255, green: 120/255, blue: 120/255, alpha: 0.5)

    // Dump the data into a single variable to shorten the code
    let stations = parsedData[indexPath.row]


    // Draw a rectangle on each progress bar depending on the availability of the bikes
    let availabilityGraph = UIBezierPath(roundedRect: CGRect(x: cell.progressView.frame.minX, y: cell.progressView.frame.minY, width: CGFloat(Float(stations.freeBikes!) / (Float(stations.freeBikes!) + Float(stations.freeDocks!))) * cell.progressView.frame.width, height: cell.progressView.frame.height), cornerRadius: 0)
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = availabilityGraph.cgPath

    //change the fill color
    shapeLayer.fillColor = UIColor.clear().cgColor
    //you can change the line width
    shapeLayer.lineWidth = cell.frame.height

    shapeLayer.strokeColor = UIColor(red: 96/255, green: 96/255, blue: 96/255, alpha: 0.8).cgColor
    cell.progressView.layer.addSublayer(shapeLayer)

    cell.bikeStationLabel.textColor = UIColor.white()
    cell.bikeStationLabel.text = stations.stationName!

    cell.distanceLabel.text = "100 m"

    return cell
}

首先給您的圖層這樣的特定名稱

shapeLayer.name = "ShapeLayer"

現在,在添加progressView視圖之前,請檢查是否尚未在progressView添加該圖層,如果已添加,則將其刪除。

if let sublayers = cell.progressView.layer.sublayers {
    for layer: CALayer in sublayers {
        if (layer.name == "ShapeLayer") {
            layer.removeFromSuperlayer()
            break
        }
    }
}
//Now add the layer to `progressView`
cell.progressView.layer.addSublayer(shapeLayer)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM