1

我正在Swift 中实现一个Circle类(的子类),它根据传入的框架在其初始化程序中设置它,如下所示:UIViewradiusinit(frame: CGRect)

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

我还想确保从 Interface Builder 实例化圆的情况,所以我还实现了'required init(coder aDecoder: NSCoder)`(无论如何我都被 Xcode 强制执行)。

如何检索frame以某种方式包含在aDecoder. 我想要实现的基本上是这样的:

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

2 回答 2

7

您可以通过以下方式设置框架计算半径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
}
于 2014-10-12T09:24:21.773 回答
3

马丁的答案是正确的。(已投票)。您可能能够找到基类对帧值进行编码并提取它的方式,但这很脆弱。(它依赖于基类实现的私有细节,这可能会在未来改变和破坏你的应用程序。)不要开发依赖于另一个类或你的基类的非公共实现细节的代码。这是一个等待发生的未来错误。

initWithCoder 中的模式是首先调用 super 来获取祖先类的值,然后提取自定义类的值。

当您这样做时,祖先类已经为您设置了视图的框架,您可以使用它。

于 2014-10-12T12:02:50.340 回答