0

When subclassing UIView, how do you access the parent classes methods and properties?... this is not working:

//
//  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)

}

Thanks

R Menke
  • 7,577
  • 4
  • 32
  • 59
cube
  • 1,714
  • 3
  • 22
  • 31

1 Answers1

3

You did not create an initialiser for the your Draw2D class. It needs this to be able to call super.init, this in turn actually creates the UIView stuff from which you are subclassing.

You also created another instance of Draw2D in your class. This is bad, if you actually do this in an initialiser (where that code belongs) it will create an infinite amount of subviews.

Recursive functions are super awesome, recursive initialiser are very bad ;)

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")
    }
}

After calling super.init() you can call stuff from the super class. Use self for extra clarity, but this is not needed.

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
R Menke
  • 7,577
  • 4
  • 32
  • 59
  • which fatal error? remove the last line, that one is for playgrounds. (which are super easy to test snippets like these.) – R Menke Sep 29 '15 at 03:02
  • When running your code. Do you see the blue square appear on the screen? – cube Sep 29 '15 at 03:07
  • 1
    No, since the code posted is only the `class Draw2D`. But that is a whole other issue. Very short : Define UIView Class -> Create Instance of UIVIew Class -> Add Instance to superView google `addSubview` for more info. – R Menke Sep 29 '15 at 03:15