0

I draw the text using Swift String.drawWithRect method. It works fine when drawing in drawRect(). But when I place the code inside dispatch_after method it isn't drawn.

Here is the code:

    let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(2)*Double(NSEC_PER_SEC)))
    dispatch_after(dispatchTime, dispatch_get_main_queue()){

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .Center
        let attrs = [NSFontAttributeName: UIFont.systemFontOfSize(12),
                     NSForegroundColorAttributeName: UIColor.grayColor(),
                     NSParagraphStyleAttributeName: paragraphStyle]

        let string = "Test"

        let x = 100.0
        let y = 100.0

        string.drawWithRect(CGRect(x: x, y: y, width: 100.0, height: 100.0), options: .UsesLineFragmentOrigin, attributes: attrs, context: nil)
    }

I guess it's related to drawing context but can't figure out what to do. How to switch context, in order to draw text using dispatch_after? Thanks in advance.

mra214
  • 509
  • 1
  • 7
  • 18
  • 3
    Why would you want to do this? You cannot do asynchronous drawing within `drawRect`. The context is specially setup for you within `drawRect` - so calling functions after `drawRect` has happened will likely lead to a crash. – Hamish Apr 07 '16 at 09:18
  • In actual code I draw scale marks in a for loop and I want them to appear one after another with a little delay. – mra214 Apr 07 '16 at 10:21
  • 1
    Okay, well that's not something `drawRect` is designed to do. You'll probably want to look into using a `CAShapeLayer` instead to draw your scale marks, and then change the `strokeEnd` property to create your effect - or use a `CADisplayLink` to re-draw your view for the intermediate steps. My answers [here](http://stackoverflow.com/a/34957671/2976878) and [here](http://stackoverflow.com/a/34964241/2976878) might be useful for this. – Hamish Apr 07 '16 at 10:38
  • Thanks. I've used CAShapeLayer for animation. – mra214 Apr 08 '16 at 08:05

0 Answers0