自定义类不在中心绘制-Swift

时间:2018-11-04 04:04:25

标签: swift uiview

我有一个带有UIView的自定义类的UIView。我试图在UIView的确切中心绘制一个点,但它出现在稍微偏离中心的底部:

UIView

自定义类在这里:

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)
    }
}

1 个答案:

答案 0 :(得分:1)

这是TimerView类的重新实现。对于UIViewinit不是获取frame/bounds值的最佳位置,因为一旦autolayout在运行时应用约束,它可能会改变。 layoutSubviews是为父/子视图获取正确的frame/bounds值并设置子空间属性的最佳位置。其次,您应该使用父视图bounds来设置孩子的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
    }
}