Custom Class Not Drawing at Center - Swift

3369 views swift
6

I have a UIView with a custom class of TimerView. I am trying to draw a dot in the exact center of the UIView but it is appearing at the bottom slightly off center:

UIView

Custom class is here:

import UIKit

class TimerView: UIView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        drawDot()
    }

    func drawDot() {

        let midViewX = self.frame.midX
        let midViewY = self.frame.midY

        let dotPath = UIBezierPath(ovalIn: CGRect(x: midViewX, y: midViewY, width: 5, height: 5))

        let dotLayer = CAShapeLayer()
        dotLayer.path = dotPath.cgPath
        dotLayer.strokeColor = UIColor.blue.cgColor

        self.layer.addSublayer(dotLayer)
    }
}

answered question

1 Answer

8

Here is the re-implementation of TimerView class. For UIView, init is not the best place to get the frame/bounds values because it might change once the autolayout applies the constraints in runtime. layoutSubviews is the best place to get the correct frame/bounds values for parent/child views and to setup the child space properties. Secondly you should be using parent view's bounds property to setup child's frame.

class TimerView: UIView {

    private var dotLayer: CAShapeLayer?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        dotLayer = CAShapeLayer()
        dotLayer?.strokeColor = UIColor.blue.cgColor
        self.layer.addSublayer(dotLayer!)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        drawDot()
    }

    func drawDot() {

        let midViewX = self.bounds.midX
        let midViewY = self.bounds.midY

        let dotPath = UIBezierPath(ovalIn: CGRect(x: midViewX, y: midViewY, width: 5, height: 5))
        dotLayer?.path = dotPath.cgPath
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.