-1

i am developing simple UITableView with custom UITableViewCell with Xib file i have added MainView and pin it to ContentView in order to add all my views inside MainView as shown below UITableViewCell layout

when i try to add CAGradientLayer to MainView it doesnt fit perfectly on mainView bounds as i show below whats happening on simulator i use this piece of code to add CAGradientLayer

    override func awakeFromNib() {
    super.awakeFromNib()
    
      let gradient = CAGradientLayer()
      mainView.layer.cornerRadius = 10
      gradient.frame = mainView.frame
      gradient.colors = [ColorCompatibility.gradEnd.cgColor, ColorCompatibility.gradStart.cgColor]
      gradient.endPoint = CGPoint(x: 0.5, y: 1)
      gradient.startPoint = CGPoint(x: 0.5, y: 0)
     // gradient.cornerRadius = 20
      
      gradient.shadowColor = ColorCompatibility.systemBackground.cgColor
      gradient.shadowOpacity = 0.8
      gradient.shadowOffset = .zero
      gradient.shadowRadius = 5
      gradient.shadowPath = UIBezierPath(roundedRect: mainView.layer.bounds, cornerRadius: 20).cgPath
      gradient.shouldRasterize = true
      gradient.rasterizationScale = UIScreen.main.scale
   
      contentView.layer.insertSublayer(gradient, at: 0)
   
    
}

how can i fix this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mamad
  • 71
  • 7

1 Answers1

0

Two issues here. The first is that in awakeFromNib the cell (and its content view) most likely doesn't have the correct frame so you could use another life cycle hook where the frame is correct but then you would run into problems when the device is rotated so the cell frame changes at runtime.

I would suggest to update the gradient layers frame in layoutSublayers(of:). Let's assume you created a property for the layer called gradient:

override func layoutSublayers(of layer: CALayer) {
    super.layoutSublayers(of: layer)

    gradient.frame = mainView.bounds
}
fruitcoder
  • 1,073
  • 8
  • 24
  • this actualy works but it hase a very little problem is that it fix the frame only when i start scrollling – Mamad Nov 09 '20 at 13:32
  • thank you so much i fix that one with LayoutIfNeeded() on viewdidapear – Mamad Nov 09 '20 at 13:41