1

Using UICollectionView under the UITableViewCell

Using below extension for creating dashed border: extension UIView {

    func addDashedLineView(frame: CGRect) {

        let border = CAShapeLayer()
        border.strokeColor = UIColor.blue.cgColor
        border.lineDashPattern = [6, 6]
        border.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)//self.frame
        border.fillColor = UIColor.clear.cgColor
        border.lineJoin = kCALineJoinRound
        //print("widht: \(frame.width) fraheight: \(UIScreen.main.bounds.width)")
        border.fillColor = nil
        border.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: frame.width, height: frame.height), cornerRadius: 6).cgPath
        self.clipsToBounds = true

        self.layer.addSublayer(border)
    }
}

Below is my collection view method where i am calling above method (actually the cell width depending upon the content size so i am calculating the text width) the issue is when the cell are dequeue from the list the border get redraw from different width, also i am using custom cell "CollectionViewCell" class:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell


       let width = self.collectionData[indexPath.row].width(withConstraintedHeight: 14, font: .systemFont(ofSize: 17)) + Constant.cellPadding
        cell.contentView.addDashedLineView(frame: CGRect(x: 0, y: 0, width: width, height: Constant.itemHeight))

        cell.contentView.setNeedsLayout()
        cell.contentView.layoutIfNeeded()
        cell.layoutIfNeeded()
        return cell
    }

When first load drawing border correctly when scroll the view it has been redraw How to resolve the issue enter image description here

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Amit Kumar Sahu
  • 495
  • 6
  • 15
  • 2
    Cells are reused you are each time calling `addDashedLineView:`. Call `addDashedLineView:` on it's init only, or at least check before adding the new layer that if there is already one, remove the old one. – Larme Nov 08 '17 at 14:52
  • i need to calculate the cell width every time, when i add layer on init() the border not expand to the cell size. how to check layer is already added or not when it display again.Thanks – Amit Kumar Sahu Nov 09 '17 at 04:53
  • When layoutSublayer, layoutSubview or `addDashedLineView:` is called, check (in pseudo code) if self.layer.sublayers.contains(myDashedSublayer), if yes, remove it, regenerate it and add it. – Larme Nov 09 '17 at 09:43

0 Answers0