0

I am programmatically creating a lot buttons in a loop and also creating a CAShapeLayer.

    for segment in innerMostSegments {
                let endAngle = startAngle + 2 * .pi * (segment.value / valueCount)
                let shape = CAShapeLayer()
                let path: UIBezierPath = UIBezierPath(arcCenter: viewCenter, radius: radius/3, startAngle: startAngle, endAngle: endAngle, clockwise: true)
                path.addLine(to: viewCenter)
                path.close()
                shape.path = path.cgPath
                shape.fillColor = segment.color.cgColor
                shape.strokeColor = UIColor.black.cgColor
                shape.borderWidth = 1.0
                shape.borderColor = UIColor.black.cgColor
                shape.name = "\(i)"
            let b = MyButton(type: .system)
            b.path = path
            b.backgroundColor = UIColor.green
            let frameRect = shape.path?.boundingBoxOfPath
            b.frame = frameRect!
            b.tag = Int(data[i-1000].asciiValues[0])
            b.addTarget(self, action: #selector(ButtonClicked(_:)), for: .touchUpInside)
            b.setTitle(data[i-1000], for: .normal)
            self.addSubview(b)
            self.bringSubviewToFront(b)
            self.isUserInteractionEnabled = true
}

The buttons are working fine but I want the buttons to be only tapped in the CAShapeLayer we have. I haven't added the shape to the view in this case. Currently, the buttons created are rectangular and hence there is a lot of overlap on the buttons. Can anyone suggest me how to achieve the same.

Thanks

dper
  • 884
  • 1
  • 8
  • 31
  • where are you adding shape in layer ? – Jawad Ali May 27 '20 at 19:03
  • @jawadAli I haven’t yet as it would make the buttons non interactive. What I want is for the buttons to get the shape of CAShapeLayer. – dper May 27 '20 at 19:05
  • The question marked as duplicate is old, but has code updated to Swift 3/4 -- and should be easily updated to Swift 5 if that's what you're using. – DonMag May 27 '20 at 19:07

0 Answers0