Last active
August 29, 2015 14:25
-
-
Save odrobnik/529db10b7030c06e1bbd to your computer and use it in GitHub Desktop.
How to make this more elegant?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Variant 1: looks inelegant | |
override internal func drawRect(rect: CGRect) | |
{ | |
let context = UIGraphicsGetCurrentContext() | |
let size = bounds.size | |
if let gradient = gradient | |
{ | |
let options = CGGradientDrawingOptions(kCGGradientDrawsAfterEndLocation) | |
var center = gradientStartPoint | |
if center == nil | |
{ | |
center = CGPoint(x: bounds.midX, y: bounds.midY) | |
} | |
CGContextDrawRadialGradient(context, gradient, center!, 0, center!, min(size.width, size.height) / 2, options) | |
} | |
} | |
// Variant 2: bad because the CGContextDrawRadialGradient appears twice | |
override internal func drawRect(rect: CGRect) | |
{ | |
let context = UIGraphicsGetCurrentContext() | |
let size = bounds.size | |
// Gradient | |
if let gradient = gradient | |
{ | |
let options = CGGradientDrawingOptions(kCGGradientDrawsAfterEndLocation) | |
if let center = gradientStartPoint | |
{ | |
CGContextDrawRadialGradient(context, gradient, center, 0, center, min(size.width, size.height) / 2, options) | |
} | |
else | |
{ | |
let center = CGPoint(x: bounds.midX, y: bounds.midY) | |
CGContextDrawRadialGradient(context, gradient, center, 0, center, min(size.width, size.height) / 2, options) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should be able to use the nil coalescing operator (
??
) to clean up that assignment tocenter
, and then not have to force unwrap it:Which cleans up the method nicely: