【问题标题】:Create UIView Subclass Without Init() - Swift?创建没有 Init() 的 UIView 子类 - Swift?
【发布时间】:2016-06-19 15:42:52
【问题描述】:

我有一个 UIView 子类,它只包含以下内容:

drawRect(rect: CGRect) {
    let ctx: CGContext? = UIGraphicsGetCurrentContext()
    let radius: CGFloat = rect.width / 2
    let endAngle = CGFloat(2 * M_PI)
    CGContextAddArc(ctx, bounds.width / 2, bounds.height / 2, radius, 0, endAngle, 1)
    CGContextSetStrokeColorWithColor(ctx, UIColor.blackColor().CGColor)
    CGContextSetFillColorWithColor(ctx, UIColor.whiteColor().CGColor)
    CGContextSetLineWidth(ctx, 4.0)
    CGContextDrawPath(ctx, CGPathDrawingMode.FillStroke)
}

我没有调用任何 init() 函数,但对象仍在绘制中。

此外,当我尝试实现一个 init() 函数时,我收到了几个关于所需初始化的错误。

所以我的问题是:如何在没有 init() 函数的情况下创建 UIView 对象?

【问题讨论】:

    标签: ios swift macos uiview core-graphics


    【解决方案1】:

    初始化器是继承的。您的超类 (UIView) 已经定义了 init,因此您的类默认继承它们。

    一旦您定义了init,您的类将不再继承超类初始化器,因此您必须定义所有必需的初始化器。

    【讨论】:

    • 只是为了澄清:如果我定义了需要什么,并调用 super.init() 我可以覆盖 init() 函数吗?
    • @BrandonBradley 是的,你可以。但是,对于UIView,更常见的是覆盖指定初始化程序init(frame:)
    • 好的,感谢您提供的信息。对此还是很陌生。
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 2022-11-13
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多