0

I'm trying to make a simple app. To do so, in part, I'm trying to use a subview to draw a circle on the screen.

This is my view controller class:

gameView is the view linked to in the the storyboard. ballView is the view I would like to add in.

class GameViewController: UIViewController {

     @IBOutlet var gameView: UIView!
     var ballView = GameBallView()

    override func viewDidLoad() {
        super.viewDidLoad()

        gameView.addSubview(ballView)
        ballView.setNeedsDisplay()
        gameView.setNeedsDisplay()
   }
}


class GameBallView: UIView {

    override func drawRect(rect: CGRect) {
        let rectForBall = CGRect(x: 50, y: 250, width: 20, height: 20)
        let path = UIBezierPath(ovalInRect: rectForBall)
        path.fill()
        path.stroke()
    }
}

drawRect is called, but for some reason nothing shows up on the screen. Does anyone know what I did wrong?

comp_sci5050
  • 145
  • 2
  • 11

1 Answers1

0

Your GameBallView, ballView, has been assigned no frame. Thus it has zero size, the default being a frame rect of CGRectZero. There is a good reason why the designated initializer of a UIView is init(frame:)! A rectangle of zero size is invisible: it is just a point, an infinitesimal.

Thus, you should be giving this view some reasonable frame that will accommodate your drawing; for example:

 var ballView = GameBallView(frame:CGRectMake(50,250,20,20))

Then, in your drawRect, draw inside the bounds of the ballView — remember, you are now drawing with respect to the ballView itself, not the game view:

let rectForBall = CGRect(x: 0, y: 0, width: 20, height: 20)

Or even better:

let rectForBall = rect // the parameter from `drawRect:`
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Okay, thanks! I did not realize that the view had to be initialized with a frame even though I was attempting to draw in the view. – comp_sci5050 Jan 25 '16 at 01:43
  • You can only draw inside the view. If the view has no size, it has no "inside". :) – matt Jan 25 '16 at 02:02
  • You might want to read my online book. On what frame and bounds are: http://www.apeth.com/iOSBook/ch14.html#_frame On UIView drawing: http://www.apeth.com/iOSBook/ch15.html#_drawing_a_uiview – matt Jan 25 '16 at 02:04