在swift中对UIView进行子类化

时间:2015-09-29 01:39:30

标签: swift uiview

当子类化UIView时,如何访问父类方法和属性?...这不起作用:

//
//  Draw2D.swift
//  Draw2D
//
import UIKit

class Draw2D: UIView {


let coloredSquare = Draw2D()
coloredSquare.backgroundColor = UIColor.blueColor()
coloredSquare.frame = CGRect(x: 0, y: 120, width: 50, height: 50)
addSubview(coloredSquare)

}

由于

1 个答案:

答案 0 :(得分:3)

您没有为Draw2D类创建初始化程序。它需要能够调用super.init,这反过来实际上创建了你从中进行子类化的UIView。

您还在班级中创建了另一个Draw2D实例。这很糟糕,如果您在初始化程序(该代码所属的地方)中实际执行此操作,则会创建无限量的子视图。

递归函数非常棒,递归初始化非常糟糕;)

import UIKit

class Draw2D: UIView {

    // this will create an infinite amount of coloredSquare's => it is a recursive initialiser
    let coloredSquare : Draw2D

    override init(frame: CGRect) {

        coloredSquare = Draw2D(frame: frame)

        super.init(frame: frame)
        self.frame = frame



        coloredSquare.backgroundColor = UIColor.blueColor()
        coloredSquare.frame = CGRect(x: 0, y: 120, width: 50, height: 50)
        addSubview(coloredSquare)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

在调用super.init()之后,你可以从超类中调用东西。使用self来获得更清晰,但这不是必需的。

class Draw2DCorrected: UIView {

    init() {

        let rect = CGRect(x: 0, y: 120, width: 50, height: 50)

        super.init(frame: rect)
        self.frame = rect // inherited stuff from super class -> UIView
        self.backgroundColor = UIColor.blueColor() // inherited stuff from super class -> UIView

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var coloredSquare = Draw2DCorrected() // playground only
相关问题