I've been programming in one way or another for 30+ years, but I'm new to Swift and iOS programming and working on my first app. I've worked out how to create a CAGradientLayer to show a gradient on screen, but I'd like to create a utility class/extension/subclass with some predefined gradients in it.
I am assuming I can do this by creating subclasses of CAGradientLayer with the properties pre-set at initialisation time, but I'm not sure of the correct syntax to do this. I guess I am missing some basic Swift requirements?
I've tried the following:
let greenBlueGradient = GreenBlueGradient.greenBlueGradient()
class GreenBlueGradient: CAGradientLayer {
override init() {
super.init()
}
func greenBlueGradient() -> GreenBlueGradient {
self.colors = [ UIColor.init( red: 0.05, green: 0.75, blue: 0.91, alpha: 1.0 ).CGColor, UIColor.init( red: 0.56, green: 0.93, blue: 0.56, alpha: 1.0 ).CGColor ]
return self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
But I'm getting the error "Missing argument for parameter #1 in call" on the let line. What am I missing? Surely there is a more efficient way of doing this? I sort of have in my head that I will be able to create some sort of utility class/extension that will return a CAGradientLayer with the colors already set ready for me to set the frame and insert it into my view hierarchy.
You shoud add an extension of CAGradientLayer in other file for exemple :
in file "UIExtensionsCAGradientLayer.swift"
extension CAGradientLayer {
func setupGreenBlurGradient(){
self.colors = [UIColor.init( red: 0.05,
green: 0.75,
blue: 0.91,
alpha: 1.0).CGColor,
UIColor.init( red: 0.56,
green: 0.93,
blue: 0.56,
alpha: 1.0 ).CGColor ]
}
}
Then in the file where you need the green blur gradient you do :
let greenGradientBlur = CAGradientLayer(layer : layer)
greenGradientBlur.setupGreenBlueGradient()
The error message here is a bit misleading. (File a bug about that. Or fix it yourself, if you're so inclined, now that Swift is open source.)
Your attempt to call GreenBlueGradient.greenBlueGradient() fails because you're calling an instance method as if it were a class method. That call would succeed if you'd declared greenBlueGradient() as a class func. However, that function's implementation relies on self.
What you probably want instead is to add your customization to init:
override init() {
super.init()
self.colors = [
UIColor(red: 0.05, green: 0.75, blue: 0.91, alpha: 1.0).CGColor,
UIColor(red: 0.56, green: 0.93, blue: 0.56, alpha: 1.0).CGColor,
]
}
That way, a client can get your custom gradient just by constructing an instance:
let greenBlueGradient = GreenBlueGradient()
Pretty colors, by the way.
Related
I have a screen of my app that uses the iOS UIMap Map. On the map there are PINs (Mark Location of Apple's Human Interface) that indicate seismometers, and every 6 seconds the map updates and some of these seismometers vibrate and turn red. I have to give the PINs on the map a fade effect, going from bright red to very light red.
if annotation.identifier == "redpin" {
view.pinTintColor = .red
DispatchQueue.main.asyncAfter(deadline: .now()+2.0 ) {
view.pinTintColor = UIColor(red: 255/255, green: 110/255, blue: 110/255, alpha: 1)
}
DispatchQueue.main.asyncAfter(deadline: .now()+2.0 ) {
view.pinTintColor = UIColor(red: 255/255, green: 180/255, blue: 180/255, alpha: 1)
}
DispatchQueue.main.asyncAfter(deadline: .now()+2.0 ) {
view.pinTintColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
}
}
I used this method, using a timer that changes the color of the PINs that vibrate every 2 seconds, giving this fade effect manually. For the first ones that vibrate on the first update this is fine, but then those that come after keep the last color (white) and not red-red light-white.
Can anyone help me?
A call to DispatchQueue.main.asyncAfter(deadline: .now()+2.0) block does not wait until it's done... the next line of code will be executed immediately.
So, in your posted code, you are effectively saying:
set the pin to Red
wait 2 seconds
set the pin to Medium Red
set the pin to Light Red
set the pin to White
You could fix this with using:
.now()+0.25 // wait 1/4 second
.now()+0.50 // wait 1/2 second
.now()+0.75 // wait 3/4 second
so each block would execute 1/4 second after the previous one.
Tint Color cannot be animated, so you cannot use it in a UIView.animate() block.
However, red-white-red Pin tint color changes do look a little "fadey" so you might be happy with:
func animPinColor(_ v: MKPinAnnotationView) -> Void {
// set pin to white
v.pinTintColor = .white
// wait 0.25 seconds ... adjust as desired
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
// set pin back to red
v.pinTintColor = .red
}
}
Or, if you want a little more control:
func animPinColor(_ v: MKPinAnnotationView) -> Void {
// verbose, for clarity
let red = UIColor(red: 255/255, green: 0, blue: 0, alpha: 1)
let mediumRed = UIColor(red: 255/255, green: 110/255, blue: 110/255, alpha: 1)
let lightRed = UIColor(red: 255/255, green: 180/255, blue: 180/255, alpha: 1)
let white = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
let colors: [UIColor] = [
mediumRed,
lightRed,
white,
lightRed,
mediumRed,
red,
]
// 1/2 second color animation ... adjust as desired
let totalDuration: Double = 0.5
// each step will take totalDuration divided by total steps
let relativeDuration = totalDuration / Double(colors.count)
for i in 0..<colors.count {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * relativeDuration) {
v.pinTintColor = colors[i]
}
}
}
You can play with the duration / timing, and could even add more "shades of red" to get an even smoother fade.
Edit
Based on the code you posted, I'm assuming you have a reference to a MKPinAnnotationView?
If so, usage would be:
if annotation.identifier == "redpin" {
//view.pinTintColor = .red
animPinColor(view)
}
I am following this tutorial provided on Youtube for: How to Save Data with UserDefaults - Swift
https://www.youtube.com/watch?v=sUhq1vIrRbo
And I have this code that works for one page only and would like to know how to do the same exact thing (changing background color) but for my entire app pages based on the user's choice.
I have tried keeping the checkForStylePreference() in the viewDidLoad()of another page but it did not recognize it. I copy pasted the whole checkForStylePreference() but still other pieces of code were missing. Is the only way to do it is by copy pasting all of the methods of the viewController in all App pages? Or there is a much simpler way as a believe to reduce amount of code? Currently I can change BgColor from white to grey perfectly enter image description here but I don't know how to apply it for all.
This is the code of my NameViewController.swift (the one I've created for the page in the screenshot). Please note that I have 2 more swift files which are SAButton.swift and ConstantStyles.swift (for the colors)
class NameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
nameLbl.text = myString
checkForStylePreference()
}
#IBAction func didChangeStyleSeg(_ sender: UISegmentedControl) {
isDarkMode = sender.selectedSegmentIndex == 1
saveStylePreference()
updateStyle()
}
var myString = String()
#IBOutlet weak var styleSegment: UISegmentedControl!
#IBOutlet weak var nameLbl: UILabel!
var isDarkMode = false
let defaults = UserDefaults.standard
struct Keys {
static let preferDarkMode = "preferDarkMode"
}
func updateStyle(){
UIView.animate(withDuration: 0.4){
// self.view.backgroundColor = self.isDarkMode ? Colors.darkGrey : .white
// UIColor(hue: 287/360, saturation: 15/100, brightness: 85/100, alpha: 1.0)
self.view.backgroundColor = self.isDarkMode ? Colors.lightGrey : .white
//recent correct one
// self.view.backgroundColor = self.isDarkMode ? Colors.darkGrey : .white
//self.view.UIBackgroundFetchResult = self.isDarkMode? UIColor.grey : .white
}
}
func saveStylePreference(){
defaults.set(isDarkMode, forKey: Keys.preferDarkMode)
}
func checkForStylePreference(){
let preferDarkMode = defaults.bool(forKey: Keys.preferDarkMode)
if preferDarkMode{
isDarkMode = true
updateStyle()
styleSegment.selectedSegmentIndex = 1
}
}
// Do any additional setup after loading the view.
}
Code of the SAButton.swift
class SAButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setupButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupButton()
}
private func setupButton() {
setTitleColor(.white, for: .normal)
backgroundColor = Colors.lightBlue
titleLabel?.font = .boldSystemFont(ofSize: 20)
layer.cornerRadius = frame.size.height / 2
}
}
Code of the ConstantStyles.swift
import UIKit
struct Colors {
static let darkGrey = UIColor(red: 40/255, green: 40/255, blue: 40/255, alpha: 1)
// static let purple = UIColor(red: 212/255, green: 186/255, blue: 86/255, alpha: 1)
static let lightBlue = UIColor(red: 89/255, green: 205/255, blue: 242/255, alpha: 1)
static let darkPurple = UIColor(red: 242/255, green: 232/255, blue: 255/255, alpha: 1.0)
// UIColor(hue: 287/360, saturation: 15/100, brightness: 85/100, alpha: 1.0)
static let lightPurple = UIColor(red: 240/255, green: 229/255, blue: 255/255, alpha: 1.0)
static let lightGrey = UIColor(red: 237/255, green: 237/255, blue: 237/255, alpha: 1.0)
//UIColor(red: 249/255, green: 244/255, blue: 255/255, alpha: 1.0)
}
I believe it could be simple but I am new to Swift, I would like to know what part of code to keep exactly and where. Much appreciated.
Ps: Original project Source Code is provided below the Youtube Video.
You can create a main class and inherit from it
class GeneralVC : UIViewController {
override func viewDidLoad() {
self.view.backgroundColor = .red // read color from userdefaults and set it here
}
}
class ViewController: GeneralVC {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Same applies to any UIKit component that you need to affect globally
Another interesting way to do it is to use Appearance:
Perhaps you can use UIViewControllerWrapperView as a parent.
UIView.appearance(whenContainedInInstancesOf: [UIViewControllerWrapperView]) // UIViewControllerWrapperView might be private. In that case it might take some wizardry to get it to work
Another way to do it is to set it when the UITabBarController or UINavigationController presents a new UIViewController. You can do this by subclassing them.
The reason why I don't like subclassing is that you force a subclass for just one simple thing. If you only do it in a few navigation based ones it's much easier and also easier to override with extensions instead of everything through subclassing.
I am working on a project where i need to apply gradients to the view. I am having sketch file and have colors which i am going to use for gradient with the locations but i am unable to get the exact view.
Can anyone please help how to get that?
I have created a function to apply gradient:-
func applyGradient(colours: [UIColor]) -> Void {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colours.map { $0.cgColor }
self.layer.insertSublayer(gradient, at: 0)
}
func applyGradientToView(){
let firstColor = UIColor(red: 26/255, green: 169/255, blue: 186/255, alpha: 1.0)
let secondColor = UIColor(red: 26/255, green: 97/255, blue: 157/255, alpha: 1.0)
let thirdColor = UIColor(red: 27/255, green: 65/255, blue: 144/255, alpha: 1.0)
self.applyGradient(colours: [firstColor, secondColor, thirdColor])
}
Here array UIcolor is a combination of colors to be used, I used all three but still, I didn't get the same as in the sketch
What I created :-
Gradient colors in sketch file:-
The view in sketch file is like this:-
Couple issues...
1) Your "Gradient colors in sketch file:" image does not match your Sketch file output image. However you applied the gradient in sketch, it is not a full top-to-bottom (or, in this case, bottom-to-top) gradient fill.
2) When working with colors in different applications and/or devices, you have to be aware of "color spaces". Take a quick search on google for sketch colors don't match and you'll find lots of material explaining it, along with tips on using sketch for iOS targets.
So, an easy way to get close to your desired output is to use OS X Digital Color Meter - which should be installed by default on your Mac (if it's not, it's easy to find). That tool allows you to hover over a point on your image and get the RGB values based on different color spaces. SRGB should be a match.
Also, there is a better way to code your custom view for reuse. Take a look at this approach:
class MyGradientView: UIView {
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() -> Void {
let gradientLayer = layer as! CAGradientLayer
let firstColor = UIColor(red: 25/255, green: 138/255, blue: 173/255, alpha: 1.0)
let secondColor = UIColor(red: 27/255, green: 163/255, blue: 184/255, alpha: 1.0)
let colours = [firstColor, secondColor]
gradientLayer.colors = colours.map { $0.cgColor }
gradientLayer.shadowColor = UIColor.black.cgColor
gradientLayer.shadowOffset = CGSize(width: 0.0, height: 1.0)
gradientLayer.shadowRadius = 2.0
gradientLayer.shadowOpacity = 0.5
gradientLayer.masksToBounds = false
}
}
Gradient layers in iOS by default go from Top-To-Bottom, so you only need your top and bottom colors defined. This approach also includes your shadow (as shown in your sketch output image). And it will maintain the gradient and shadow when using the custom view with auto-layout:
let v = MyGradientView()
view.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
v.topAnchor.constraint(equalTo: view.topAnchor, constant: 100.0).isActive = true
v.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100.0).isActive = true
v.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0).isActive = true
v.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40.0).isActive = true
Result:
According to the documentation of CAGradientLayer (https://developer.apple.com/documentation/quartzcore/cagradientlayer) to specify a location of colors you can use locations property(in your case [0, 0.68, 1]):
var locations: [NSNumber]? { get set }
but as #Alladinian wrote in the comment in your example, it looks like your gradient was drawn from bottom to top and start before view and end far after view so you see only a part
I have the following subclass:
class GeneralNavigationBar: UINavigationBar {
override func layoutSubviews() {
super.layoutSubviews()
self.barTintColor = UIColor(rgb: 0x2A5298) //Extension that converts hex to color
self.tintColor = UIColor.white
}
}
I want the title of the bar to be white. When I apply this class to a NavigationBar in the storyboard, the background gets blue (hex, as he is supposed to), but the title remains black.
It's strange, since you can alter the color of the bar in the ViewController it appears in:
self.navigationController?.navigationBar.barTintColor = UIColor(red: 204/255, green: 47/255, blue: 40/255, alpha: 1.0)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
This works.
Try appearance,see how..
var navbarappearace = UINavigationBar.appearance()
navbarappearace.barTintColor = UIColor(red: 204/255, green: 47/255, blue: 40/255, alpha: 1.0)
navbarappearace.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
Put the above code in AppDelegate, it should affect the whole project.
Cheers.
I want to change the text and the background color of the view on tap. The quotes are changing, but the view background color don't change. What am I doing wrong?
Here is the code:
import UIKit // UI: user interface
class ViewController: UIViewController {
// IB: Interface Builder
#IBOutlet weak var quoteLabel: UILabel!
var quotes = Quotes()
// gets called when the view is loaded
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// Interface Builder Action.
// Gets called whenever the user taps on the button
#IBAction func inspireMeDidTap(sender: UIButton)
{
let quote = quotes.randomQuote()
quoteLabel.text = quote
// change the background color of the view
view.backgroundColor = randomColor()
}
func randomColor() -> UIColor
{
let random = Int(arc4random()) % 5 // 0 -> 4
switch random {
case 0: return UIColor(red: 211/255.0, green: 86/255.0, blue: 87/255.0, alpha: 0)
case 1: return UIColor(red: 71/255.0, green: 178/255.0, blue: 137/255.0, alpha: 0)
case 2: return UIColor(red: 229/255.0, green: 177/255.0, blue: 93/255.0, alpha: 0)
case 3: return UIColor(red: 92/255.0, green: 163/255.0, blue: 178/255.0, alpha: 0)
case 4: return UIColor(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 0)
default: return UIColor(red: 56/255.0, green: 72/255.0, blue: 72/255.0, alpha: 0)
}
}
}
try this:
put all alpha = 1 in your colors (instead of 0).
If alpha = 0, entirely transparent
Meaning of alpha
You are setting alpha parameter to zero it means whatever the color is it will be completely transperent(not white).
So what you need to do is just set alpha to 1 and you will get your correct color