2016-07-21 16 views
1

私のカスタムUITableViewの中にUIViewを追加して、可用性バーの多かれ少なかれを描画します。私はそれに2つの問題があります:スクロール時にカスタムUITableViewCellのUIViewが再描画されます

1.-ビューは、起動時ではなく新しいセルが画面上に表示されたときに描画されます。これは、以下のGIFで見ることができます。

2.- tableView数回スクロールすると、彼らはのUITableViewCellの相互

GIF

コードと重複するように、各セルのUIViewが再描画される:

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 
} 

答えて

2

まず、それをその層が既にprogressViewに追加されていないprogressViewチェックを追加する前に、今、この

shapeLayer.name = "ShapeLayer" 

のようなあなたの層固有の名前を付けそれを取り除くだけです。

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) 
+0

ちょうど試しました。クラッシュする、古典的なオプションのアンラッピングエラー: '致命的なエラー:予期せず、オプション値をアンラッピングしながらnilが見つかりました'。私はあなたが提案したものだけを追加しました。[screenshot](http://imgur.com/a/UxD2r) – jdmg718

+0

私の編集した答えをチェックしてください。これはあなたのクラッシュを解決します。 –

+0

私の編集した答えを試しましたか? –