nwales
nwales

Reputation: 3561

@IBDesignable UiView draw(_ rect: CGRect) works in IB but not on device

I have a circle progress in a draw rect function that is a subclass of UIControl. Swift 3, Xcode 8.

It looks like this:

override func draw(_ rect: CGRect) {
        super.draw(rect)

        guard let ctx = UIGraphicsGetCurrentContext() else {
            return
        }

        let center = CGPoint(x:rect.size.width/2.0,y:rect.size.height/2.0)
        ctx.setStrokeColor(UIColor.cyan.cgColor)
        ctx.setLineWidth(40)
        ctx.setLineCap(.round)
        ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
        ctx.drawPath(using: .stroke)
}

This view is being added programmatically to a @IBDesignable UIViewSubclass

override func awakeFromNib() {
        super.awakeFromNib()
        self.backgroundColor = UIColor.yellow

        self.circleTest = TestCircle(frame: self.bounds)
        self.addSubview(circleTest!)
        setupConstraints() //pins subview to edges of self.
    }

Where have I gone wrong?

enter image description here

Upvotes: 1

Views: 611

Answers (1)

Rob
Rob

Reputation: 438477

The issue is that the setting of radius. In comments you point out that you're setting it in init, and you obviously have to allow for subsequent changes in the frame (esp when using auto layout), so you could move the assignment of radius into draw(_:) (or, if you weren't using draw(_:), but rather CAShapeLayer or the like, you could do it in layoutSubviews()).

Upvotes: 1

Related Questions