2015-09-29 68 views
0

当继承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) 

} 

感谢

+0

这些天,使用容器视图http://stackoverflow.com/a/23403979/294884 – Fattie

回答

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(),您可以从超一流的呼叫东西之后。使用自我来增加清晰度,但这不是必需的。

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 
+0

这段代码被'致命错误'捕获。 – cube

+0

哪个致命错误?删除最后一行,那一行是为了操场。 (这些测试片段非常容易测试)。 –

+0

运行代码时。你看到蓝色方块出现在屏幕上吗? – cube