I had to write code to show a variable-sized set of images in a view. Each mage fades in then shows for another 5 seconds before the next image fades in. I found some code at Stack Overflow that was partially complete and hinted at a way to do this. Since people tend to just show code snippets and not complete classes online, I decided I would share my code. I think that since I get a lot of code examples from online, that I should give a little back to the community by sharing the results of my work.

The ImageFadeView class is a view that can be given an array of images and it will cycle between them endlessly by fading in each new image. The class uses two child image views and the top image view either fades in to show its image or fades out to reveal the image in the view behind it.

This is the first draft of this code file. It works but there are a few changes I want to make. Mostly, I want to simplify some of the code and remove code that doesn’t do anything important, like setting the frame of the child views when they are created – they get sized whenever the parent get a layoutSubviews() call. I also didn’t worry much about making the timing variable and I should not have it hard-coded like this. But since this will only have this one use in my project, this wrks for me.

And yes, I see where I wrote that comment incorrectly and the image is covered up by the one above it in the Z-order. And scaleToFillSize() is not used anywhere but is here because this file started out as an image carousel view that had a ton of other functions that got deleted for this impelementation. I just missed scaleToFillSize().

I almost forgot to include the extension to the UIView class that handles the fades…

I copied this fadeIn, fadeOut code from the internet. I didn’t write it and I very much aopreciate that soeone else shared it so I could have this functionality without spending time duplicatig their efforts.

It took me a while to understand how the animations work in iOS. I could never figure out at first how you would set the alpha value to 1.0 and have it animate. Then I learned that iOS supports specific memebers of view classes for animations and the animation is handled internally somehow. So set the value to 1.0 in an animation and the operating system does the increment or decrement as neded.