Search code examples
iosobjective-cswiftdrawrectnscoder

Get property from NSCoder in required init(coder aDecoder: NSCoder)


I am implementing a Circle class (subclass of UIView) in Swift that sets its radius in its initializer according to the frame that is passed in init(frame: CGRect) like so:

override init(frame: CGRect)
{
    radius = frame.width/2.0
    super.init(frame: frame)
}

I also want to ensure for the case when the circle is instantiated from Interface Builder, so I also implement 'required init(coder aDecoder: NSCoder)` (which I am forced to do by Xcode anyway).

How can I retrieve the frame property of the view that is somehow contained in aDecoder. What I want to achieve basically would look like this:

required init(coder aDecoder: NSCoder)
{
   var theFrame = aDecoder.someHowRetrieveTheFramePropertyOfTheView // how can I achieve this?
   radius = theFrame.width/2.0
   super.init(coder: aDecoder)
}

Solution

  • You could compute the radius after the frame has been set by super.init():

    required init(coder aDecoder: NSCoder)
    {
        radius = 0 // Must be initialized before calling super.init()
        super.init(coder: aDecoder)
        radius = frame.width/2.0
    }