1

The following class implements a view with a striped pattern background. It works fine in iOS 11, but crashes with EXC_BAD_ACCESS in iOS 12 on the call to load(as:) in the callback method.

Any pointers to what I'm doing wrong would be welcome.

import UIKit

class LinedView: UIView {
  var colors: [UIColor] = [] {
    didSet {
      setNeedsDisplay()
    }
  }

  override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else { return }

    var patternCallback = CGPatternCallbacks(
      version: 0,
      drawPattern: {pointer, context in
        guard let colors = pointer?.load(as: [UIColor].self) else { return }
        for (index, color) in colors.enumerated() {
          context.setFillColor(color.cgColor)
          context.fill(CGRect(x: CGFloat(index) * 2 + CGFloat(index - 1) + 1, y: 0, width: 2, height: 1))
        }

    },
      releaseInfo: nil
    )

    let width = CGFloat(colors.count * 3)
    withUnsafeMutablePointer(to: &colors) {
      guard let pattern = CGPattern(
        info: $0,
        bounds: .init(x: 0, y: 0, width: width, height: 1),
        matrix: .identity,
        xStep: width + 1,
        yStep: 1,
        tiling: .constantSpacingMinimalDistortion,
        isColored: true,
        callbacks: &patternCallback
        ) else { return }

      if let patternSpace = CGColorSpace(patternBaseSpace: nil) {
        context.setFillColorSpace(patternSpace)
        var alpha: CGFloat = 1
        context.setFillPattern(pattern, colorComponents: &alpha)
        context.fill(rect)
      }
    }
  }
}
Rudedog
  • 4,323
  • 1
  • 23
  • 34
  • Duplicate of https://stackoverflow.com/questions/44211720/trouble-using-callbacks-with-cgpattern-in-swift3 where the matter seems to me quite thoroughly explained in the answers. – matt Sep 13 '18 at 17:01

0 Answers0