0

Create a simple app, and can't do it without an error

Code

I don't really know why bg.drawInRect doesn't cause an error when player.drawInRect causing? And the problem is that image doesn't drawing/redrawing when we change coordinates

Sep 16 22:13:16 imac-admin.lan Letalka_drawrect[804] : CGContextRestoreGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

Olexiy Pyvovarov
  • 870
  • 2
  • 17
  • 32

1 Answers1

1

You need to start your timer outside your drawRect call; didMoveToSuperview might be a good place, but it depends on what you're trying to accomplish. Then, in timerRedraw, call setNeedsDisplay() to trigger a re-draw.

var timer: NSTimer?

override func didMoveToSuperview() {
    // Stop the timer if it was already running
    if timer != nil {
        timer.invalidate()
        timer = nil
    }

    // Only start the timer if the view is actually part of a view hierarchy
    if superview != nil {
        timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "timerRedraw", userInfo: nil, repeats: true)
    }
}

func timerRedraw() {
    x += 5
    y += 6
    setNeedsDisplay()
}

I highly recommend reading Apple's Drawing and Printing Guide for iOS, it explains everything you need to know to get started with doing custom drawing in iOS.

Mike S
  • 41,895
  • 11
  • 89
  • 84
  • Working best, but a little correction needs I need to use a func setNeedsDisplayInRect(rect : CGRect) This works setNeedsDisplayInRect(CGRectMake(x-5,y-6, rocket.size.width,rocket.size.height)) – Olexiy Pyvovarov Sep 16 '14 at 20:14
  • `drawRect` has a `rect` parameter which is used to determine which part of your view needs to be drawn. `setNeedsDisplayInRect(rect:)` will pass the `CGRect` you give it on to your `drawRect` function; `setNeedsDisplay()` will pass the `bounds` of your view to `drawRect` instead. Since you don't seem to be using the `rect` parameter in your `drawRect` function you must be redrawing your entire view each time it's called. `setNeedsDisplay()` seems like the more appropriate function to use in that case. – Mike S Sep 16 '14 at 20:26
  • Mike, could you give me the link, where I could read how to format the code in comment, 'cause I'm trying to use > \t but it doesn't help – Olexiy Pyvovarov Sep 16 '14 at 20:30
  • 1
    @OlexiyPyvovarov When you add a comment, there's a little "help" link under the "Add Comment" button. Click that to see the formatting available. – Mike S Sep 16 '14 at 20:32