Set UIColor in storyboard from variable/constant [duplicate] - swift

This question already has answers here:
How to change dynamically color used in UIStoryboard
(2 answers)
Closed 4 years ago.
How do I set, let's say a text color on a UILabel, to a color defined in one of my classes like:
func mainAppColor() -> UIColor {
return UIColor(red: 0.2, green: 0.3, blue: 0.4, alpha: 1)
}
or
let mainAppColor = UIColor(red: 0.2, green: 0.3, blue: 0.4, alpha: 1)
in storyboard.

If your method is declared in some other class like:
class TextColorClass {
func mainAppColor() -> UIColor {
return UIColor(red: 0.2, green: 0.3, blue: 0.4, alpha: 1)
}
}
Then you can use it by make instance of that class this way:
let classInstance = TextColorClass()
yourLBL.textColor = classInstance.mainAppColor()
If it is declared like:
class TextColorClass {
let mainAppColor = UIColor(red: 0.2, green: 0.3, blue: 0.4, alpha: 1)
}
Then you can use it like:
let classInstance = TextColorClass()
yourLBL.textColor = classInstance.mainAppColor
If that method is declare in same class suppose in ViewController class then you can use it this way:
override func viewDidLoad() {
super.viewDidLoad()
yourLBL.textColor = mainAppColor()
}
func mainAppColor() -> UIColor {
return UIColor(red: 0.2, green: 0.3, blue: 0.4, alpha: 1)
}
UPDATE:
If you want to set any property from storyboard you can use #IBInspectable as shown in below example code:
import UIKit
#IBDesignable
class PushButtonView: UIButton {
#IBInspectable var fillColor: UIColor = UIColor.greenColor()
#IBInspectable var isAddButton: Bool = true
override func drawRect(rect: CGRect) {
}
}
And assign this class to your button.like shown into below Image:
And if you go to the Attribute Inspector you can see custom property for that button.
Now you can set it as per your need.
For more Info refer this tutorial:
http://www.raywenderlich.com/90690/modern-core-graphics-with-swift-part-1

Related

How to set alpha for an Assets Color in Swift

I just wanted to know how to change the opacity (alpha) of an asset color I have. When I try this UIColor(named: "something", alpha: 0.4), Xcode complains: Extra argument 'alpha' in call.
Is there any way I can modify the opacity of an asset color programmatically?
UIColor, as mentioned by Jasur S., has the withAlphaComponent(_:).
It can be used with any UIColor objects to modify its alpha:
let color = UIColor(named: "something")?.withAlphaComponent(0.5)
Creating custom extensions to cover existing functionality is an arguable good.
You can add this extension for UIColor and easy to use.
extension UIColor {
convenience init?(named: String, alpha: CGFloat) {
if let rgbComponents = UIColor(named: named)?.cgColor.components {
self.init(red: rgbComponents[0], green: rgbComponents[1], blue: rgbComponents[2], alpha: alpha)
} else {
self.init(named: named)
}
}
}
Usage:
let colorWithAlpha = UIColor(named: "Assets Color", alpha: 0.5)
You can set color alpha component when you assign color as follows:
button.backgroundColor = .black.withAlphaComponent(0.5)
You can modify asset color from here
Select that particular asset color and
Drag that opacity indicator in left or right or directly set some values
Use this extension to get the rgb value from the UIColor
extension UIColor {
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)
}
}
Then you can create a new color
let assetColor = UIColor(named: "something")
let (r,g,b,_) = assetColor.rgba
let newColor = UIColor(red:r, green:g, blue:b, alpha: 0.4)

Why is my Gradient Layer smaller than the UITextField I am applying it to?

I am trying to give my text fields a gradient background. I am using the following code:
import UIKit
extension UITextField {
func gradientBackground(firstColor: UIColor, secondColor: UIColor){
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x:0.0, y:0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
layer.addSublayer(gradientLayer)
}
}
class gradientTeLabel: UITextField {
override func didMoveToWindow() {
self.gradientBackground(firstColor: UIColor(red: 0.90, green: 0.61, blue: 0.00, alpha: 1), secondColor: UIColor(red: 0.70, green: 0.61, blue: 0.70, alpha: 1))
}
}
What I did was to create an extension and a class which I will attach to some UITextFields. The result is the gradient layer is a little bit shorter than the textfield and it kind of starts a few pixels higher inside the texfield instead of covering it all. What can I do?
Move code to layoutSubviews , As it contains the right bounds
class gradientTeLabel: UITextField {
var once = true
override func layoutSubviews() {
super.layoutSubviews()
if once {
self.gradientBackground(firstColor: UIColor(red: 0.90, green: 0.61, blue: 0.00, alpha: 1), secondColor: UIColor(red: 0.70, green: 0.61, blue: 0.70, alpha: 1))
once = false
}
}
}

Swift right CustomColor class declaration

because of strange color solutions in swift i needed to make customcolor class. And i dont know am i doing right.
i have a class CustomColors()
and usage: color = CustomColors().black and works perfectly
but i want to make use like: color = CustomColors(.Black)
i cant do like this:
init(_ Color: Colors)
{
switch Colors
case .Black
return UIColor(r:255,g:255,b:255,a:255)
}
A lot of things i dont know. Can someone put me on right solution? Thank you.
Instead of custom class you can use an UIColor extension with convenience initializer, as such:
extension UIColor {
convenience init(color: Colors) {
switch color {
case .black:
self.init(red: 1, green: 1, blue: 1, alpha: 1)
case .white:
self.init(red: 1, green: 1, blue: 1, alpha: 1)
}
}
}
But I think its better if you pre-define your colors using struct's static properties, as such:
struct Theme {
static let colorOne = UIColor(red: 0.952941, green: 0.952941, blue: 0.952941, alpha: 1.0) // F3F3F3
static let colorTwo = UIColor(red: 0.203922, green: 0.203922, blue: 0.203922, alpha: 1.0) // 343434
// and so on...
}
Usage
UILabel().backgroundColor = Theme.colorOne
UILabel().textColor = Theme.colorTwo
you can add extension to UIColor class with your custom colors:
import UIKit
extension UIColor {
static var mediumTurquoise: UIColor {
return UIColor(red:0.31, green:0.82, blue:0.8, alpha:1)
}
}
please be sure that the value of RGB between 0.0 and 1.0.
you can user the custom color as UIolor.mediumTurquoise

How to make a random color with Swift

How I can make a random color function using Swift?
import UIKit
class ViewController: UIViewController {
var randomNumber = arc4random_uniform(20)
var randomColor = arc4random()
//Color Background randomly
func colorBackground() {
// TODO: set a random color
view.backgroundColor = UIColor.yellow
}
}
You're going to need a function to produce random CGFloats in the range 0 to 1:
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
Then you can use this to create a random colour:
extension UIColor {
static func random() -> UIColor {
return UIColor(
red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0
)
}
}
If you wanted a random alpha, just create another random number for that too.
You can now assign your view's background colour like so:
self.view.backgroundColor = .random()
For Swift 4.2
extension UIColor {
static var random: UIColor {
return UIColor(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0
)
}
}
For Swift 3 and above:
extension CGFloat {
static var random: CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static var random: UIColor {
return UIColor(red: .random, green: .random, blue: .random, alpha: 1.0)
}
}
Usage:
let myColor: UIColor = .random
Make a function to generate random color:
func getRandomColor() -> UIColor {
//Generate between 0 to 1
let red:CGFloat = CGFloat(drand48())
let green:CGFloat = CGFloat(drand48())
let blue:CGFloat = CGFloat(drand48())
return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}
Now, you can call this function whenever you need random color.
self.view.backgroundColor = getRandomColor()
For random solid colors you can use UIColor HSB initializer and randomize only the hue:
extension UIColor {
static var random: UIColor {
return .init(hue: .random(in: 0...1), saturation: 1, brightness: 1, alpha: 1)
}
}
let color1: UIColor = .random
let color2: UIColor = .random
let color3: UIColor = .random
let color4: UIColor = .random
let color5: UIColor = .random
SwiftUI - Swift 5
import SwiftUI
extension Color {
static var random: Color {
return Color(red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1))
}
}
Usage:
let randomColor: Color = .random
With Swift 4.2, you can simplify this by using the new random functions which have been added:
extension UIColor {
static func random () -> UIColor {
return UIColor(
red: CGFloat.random(in: 0...1),
green: CGFloat.random(in: 0...1),
blue: CGFloat.random(in: 0...1),
alpha: 1.0)
}
}
There are more details here.
Swift 4.2 🔸
I'm adding this answer because it uses a different approach, and because many of the previous answers requires additional syntactic sugar, which in my opinion shouldn't be preferred. Vanilla Swift for the win.
extension UIColor {
/**
* Returns random color
* ## Examples:
* self.backgroundColor = UIColor.random
*/
static var random: UIColor {
let r:CGFloat = .random(in: 0...1)
let g:CGFloat = .random(in: 0...1)
let b:CGFloat = .random(in: 0...1)
return UIColor(red: r, green: g, blue: b, alpha: 1)
}
}
Swift 4.2 Extension
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
static func random() -> UIColor {
return UIColor(rgb: Int(CGFloat(arc4random()) / CGFloat(UINT32_MAX) * 0xFFFFFF))
}
}
Usage:
let color = UIColor.random()
Swift 5.1
Make This function and generate Random color.
e.g. view.backgroundColor = random()
func random() -> UIColor {
return UIColor(red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0)
}
Using an extension with an inline function to generate randoms
extension UIColor {
static func random() -> UIColor {
func random() -> CGFloat { return .random(in:0...1) }
return UIColor(red: random(),
green: random(),
blue: random(),
alpha: 1.0)
}
}
func anotherGetRandomColor()->UIColor{
let newRed = Double(arc4random_uniform(256))/255.0
let newGreen = Double(arc4random_uniform(256))/255.0
let newBlue = Double(arc4random_uniform(256))/255.0
return UIColor(red: CGFloat(newRed), green: CGFloat(newGreen), blue: CGFloat(newBlue), alpha: 1.0)
}

Swift: using member constant as default value for function parameter

I have a swift class, in which I am trying to pass a default value for a function parameter:
class SuperDuperCoolClass : UIViewController {
// declared a constant
let primaryColor : UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)
// compilation error at below line: SuperDuperCoolClass.Type does not have a member named 'primaryColor'
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = primaryColor){
// some cool stuff with bullet and primaryColor
}
}
As stated above, if I try to use constant as default value for function parameter, compiler complains with below error:
SuperDuperCoolClass.Type does not have a member named 'primaryColor'
but if I assign the RHS value directly like this, it does not complain :-/ :
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)) {
// now I can do some cool stuff
}
Any ideas on how can I silence the above compilation error?
You have to define the default value as a static property:
class SuperDuperCoolClass : UIViewController {
static let primaryColor : UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = primaryColor){
}
}
The above code compiles with Swift 1.2 (Xcode 6.3) which added support
for static computed properties. In earlier versions, you can define
a nested struct containing the property as a workaround (compare
Class variables not yet supported):
class SuperDuperCoolClass : UIViewController {
struct Constants {
static let primaryColor : UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)
}
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = Constants.primaryColor){
}
}
Since primaryColor is an instance variable it cannot be accessed until an instance is created from this class and since the function is part of the class definition you will get this error as primaryColor cannot access at that time.
You can either use MartinR approach or use your approach with the desired color:
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)) {
// now I can do some cool stuff
}