I\'m using a horizontal UIScrollView, and I want a background color transition depending on the x value of the content offset.
Example: The width o
Inspired by @Fogmeister's answer I put the pieces together in swift.
extension UIColor {
static func color(between start: UIColor, and end: UIColor, percentage: CGFloat) -> UIColor {
let startRGB = start.rgba
let stopRGB = end.rgba
let red: CGFloat = (stopRGB.red - startRGB.red) * percentage + startRGB.red
let green: CGFloat = (stopRGB.green - startRGB.green) * percentage + startRGB.green
let blue: CGFloat = (stopRGB.blue - startRGB.blue) * percentage + startRGB.blue
let alpha: CGFloat = (stopRGB.alpha - startRGB.alpha) * percentage + startRGB.alpha
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (red, green, blue, alpha)
}
}
Now you can do something like this:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
let scrolledDistance = offset + scrollView.contentInset.top
let progress = max(0, min(1, scrolledDistance / scrollView.contentSize.height))
someLabel.textColor = .color(between: .red, and: .green, percentage: progress)
}
Warning: This implementation will trigger swiftlints large_tuple rule. But you can disable, simply add ' - large_tuple' into disabled_rules section.