So I'm working on a iOS application written in Swift and I came across this exact same issue as this:
CAGradientLayer not resizing nicely.
I add a CAGradientLayer to my UIView and I override willAnimateRotationToInterfaceOrientation in order to update the gradient bounds. This only seems to update AFTER the rotation is complete and thus you see the bounds of the original frame when rotating (which causes the user to see the white background of my app).
Here is my code:
in viewDidLoad, I have the following code:
var color1: UIColor = UIColor(red: CGFloat(0.12), green: CGFloat(0.13), blue: CGFloat(0.70), alpha: CGFloat(1.0))
var color2: UIColor = UIColor(red: CGFloat(0.00), green: CGFloat(0.59), blue: CGFloat(1.00), alpha: CGFloat(1.0))
var color3: UIColor = UIColor(red: CGFloat(0.00), green: CGFloat(1.00), blue: CGFloat(1.00), alpha: CGFloat(1.0))
let gradient : CAGradientLayer = CAGradientLayer()
let arrayColors: [AnyObject] = [color1.CGColor, color2.CGColor, color3.CGColor]
gradient.frame = self.view.bounds
gradient.colors = arrayColors
view.layer.insertSublayer(gradient, atIndex: 0)
and I override this function:
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
var gradient:CAGradientLayer = self.view.layer.sublayers[0] as CAGradientLayer
gradient.frame = self.view.bounds
}
The solution is seems to be this:
// GradientView.h
@interface GradientView : UIView
@property (nonatomic, strong, readonly) CAGradientLayer *layer;
@end
// GradientView.m
@implementation GradientView
+ (Class)layerClass {
return [CAGradientLayer class];
}
@end
But I'm having a really hard time converting this class to Swift. Can someone help me? So far I have this:
import Foundation
import UIKit
class GradientView:UIView
{
var gradientLayer:CAGradientLayer = CAGradientLayer()
func layerClass() -> CAGradientLayer {
return gradientLayer.self
}
}
But it doesn't seem to work. I'm not understanding what would be the Swift equivalent of the 'class' message being used in [CAGradientLayer class]?
I've been trying to make this work for a few hours now and I just can't seem to get it. Any help would be highly appreciated!
Thanks