0

I have an app on tvOS and collection view with horizontal scroll. When the item is focused the ImageView grows a bit. I also added gradient border to focused ImageView inside this cellView. I'm adding gradient border based on this answer https://stackoverflow.com/a/62091073/4037291

public extension UIView {

private static let kLayerNameGradientBorder = "GradientBorderLayer"

func gradientBorder(width: CGFloat,
                    colors: [UIColor],
                    startPoint: CGPoint = CGPoint(x: 0.5, y: 0.0),
                    endPoint: CGPoint = CGPoint(x: 0.5, y: 1.0),
                    andRoundCornersWithRadius cornerRadius: CGFloat = 0) {

    let existingBorder = gradientBorderLayer()
    let border = existingBorder ?? CAGradientLayer()
    border.frame = CGRect(x: bounds.origin.x, y: bounds.origin.y,
                          width: bounds.size.width + width, height: bounds.size.height + width)
    border.colors = colors.map { return $0.cgColor }
    border.startPoint = startPoint
    border.endPoint = endPoint

    let mask = CAShapeLayer()
    let maskRect = CGRect(x: bounds.origin.x + width/2, y: bounds.origin.y + width/2,
                          width: bounds.size.width - width, height: bounds.size.height - width)
    mask.path = UIBezierPath(roundedRect: maskRect, cornerRadius: cornerRadius).cgPath
    mask.fillColor = UIColor.clear.cgColor
    mask.strokeColor = UIColor.white.cgColor
    mask.lineWidth = width

    border.mask = mask

    let exists = (existingBorder != nil)
    if !exists {
        layer.addSublayer(border)
    }
}
private func gradientBorderLayer() -> CAGradientLayer? {
    let borderLayers = layer.sublayers?.filter { return $0.name == UIView.kLayerNameGradientBorder }
    if borderLayers?.count ?? 0 > 1 {
        fatalError()
    }
    return borderLayers?.first as? CAGradientLayer
}

}

In general it works fine but sometimes when I scroll fast the border doesn't reflect size of the view. The image bellow shows how the border looks when I scroll fast.

wrong_focus_on_image

I'm adding gradient border to and image like this.

view.logoView.addGradientBorder(
     width: 4,
     colors: AppTheme.Color.gradient,
     startPoint: .topLeft,
     endPoint: .bottomRight,
     andRoundCornersWithRadius: 4
 )

The borders should be around image even after fast scroll. Thank you for your help.

Matt199
  • 264
  • 2
  • 18
  • If the image change its size, then you need to change the frame (or redraw) its layers gradients. – Larme Nov 03 '22 at 16:19
  • Thanks, but it only happens when I fast scroll. When I scroll normally (slow) the gradient is displaying correctly – Matt199 Nov 03 '22 at 16:36
  • It seems to be the same issue like in `UICollectionView` (for instance): https://stackoverflow.com/questions/51192224/uicollectionviewcell-multiple-cell-size-set-gradientview-width-not-set-to-the – Larme Nov 03 '22 at 16:47

0 Answers0