初始化 UIView 子类属性如何影响 superview 的中心?

How does initializing UIView subclass properties affect superview's center?

我的 UIView 子 class 中的 graphOrigin 属性 有问题。当我将 graphOrigin 定义为计算变量时,它将超级视图的中心点转换为该视图的中心点,并在屏幕中央显示图形。当不计算变量时,不会发生这种情况。查看工作案例的代码和屏幕截图:

class GraphX_YCoordinateView: UIView {

    var graphOrigin: CGPoint {
        return convertPoint(center, fromView: superview)
    }

    @IBInspectable var scale: CGFloat = 50 {
        didSet {
            setNeedsDisplay()
        }
    }

    override func drawRect(rect: CGRect) {

        // Draw X-Y axes in the view
        let axesDrawer = AxesDrawer(contentScaleFactor: contentScaleFactor)
        axesDrawer.drawAxesInRect(bounds, origin: graphOrigin, pointsPerUnit: scale)
    }

}

AxesDrawer 是一个 class 在当前视图中绘制坐标轴的工具,这里是 drawAxesInRect 的方法签名:

drawAxesInRect(bounds: CGRect, origin: CGPoint, pointsPerUnit: CGFloat)

下面是无效案例的代码和屏幕截图:

class GraphX_YCoordinateView: UIView {

    var graphOrigin: CGPoint! {
        didSet {
            setNeedsDisplay()
        }
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        graphOrigin = convertPoint(center, fromView: superview)
    }

    @IBInspectable var scale: CGFloat = 50 {
        didSet {
            setNeedsDisplay()
        }
    }

    override func drawRect(rect: CGRect) {

        // Draw X-Y axes
        let axesDrawer = AxesDrawer(contentScaleFactor: contentScaleFactor)
        axesDrawer.drawAxesInRect(bounds, origin: graphOrigin, pointsPerUnit: scale)
    }
}

所以从字面上看,我所做的所有更改都是在适当的位置初始化 graphOrigin 属性 并在初始化程序中计算它。我在编辑这段代码时根本没有接触 StoryBoard。

我尝试初始化内联变量:

var graphOrigin = convertPoint(center, fromView: superview)

但这是不允许的,因为隐式 self 在计算属性时未初始化。

谁能解释为什么 superview 的中心似乎会根据变量的初始化方式改变位置?

这个函数

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    graphOrigin = convertPoint(center, fromView: superview)
}

表示你是从xib加载view,此时view维度为600:600(看你的xib)。这样你的graphOrigin = 300:300。这就是你看到第二张图片的原因。

要解决该问题,您应该在 viewDidLayout 中的视图完成布局后计算 graphOrigin