I have a UIView with a backgroundcolor.
@IBOutlet var timelineview: Timelineview!
Now I would like the change the background color of the UIView
with an Asynctask which should change the backgroundcolor of the UIView
every second.
dispatch_async(dispatch_get_main_queue()) {
for var i=10;i<100;i++ {
println(i);
var iRed:CGFloat=CGFloat(i)/CGFloat(10.0);
var backgroundColor:UIColor=UIColor(red: iRed, green: iRed, blue: iRed, alpha: 0.5);
self.timelineview.backgroundColor = backgroundColor;
sleep(1);
}
}
This is only a sample to understand how to invoke a change to the GUI from a background task. In Android this is done with handlers, which are updating the GUI. I don't know the concept in IOS doing this.
Any help ?
What you are actually looking for is not a dispatch queue, rather a timer that can be created using dispatch_source_create
method of GCD, like following:
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main-queue());
//start timer
if (timer) {
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, interval * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
// set background color or any other UI code here
});
dispatch_resume(timer);
}
interval
is the interval in seconds in which the timer should fire (1.0 for you)
To stop the timer use:
dispatch_source_cancel(timer);
timer = NULL;
I am sorry, that I am a plain old Objective C guy and not much familiar with Swift. But you might get the concept.