So, while working in swift, i made a view in a viewController where when I tap another view in the same ViewController, it generates an array with value
[arc4random_uniform(257), arc4random_uniform(257), arc4random_uniform(257)]
where the random numbers are parameters for random RBG colors, and I've only sort-of made it work. I want it so that every time the user (or me ;_;) taps on the view with the Tap Gesture Recognizer, it generates another random color. I don't really know how to "re-roll" the Array so that it generates another random color.
If you want to get just a random UIColor, you can create a function which gets called everytime you touch the recognizer. Also, as mattt mentioned in the comments, you should change the max value from 257 to 256.
func randomColorCreator()->UIColor{
var red:CGFloat = CGFloat(arc4random_uniform(256))/CGFloat(255)
var green:CGFloat = CGFloat(arc4random_uniform(256))/CGFloat(255)
var blue:CGFloat = CGFloat(arc4random_uniform(256))/CGFloat(255)
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
If you really want to get the three color-values, you can return the three values like that:
func randomColorCreatorV2()->(red:Int, green:Int, blue:Int){
var red: = arc4random_uniform(256)
var green: = arc4random_uniform(256)
var blue: = arc4random_uniform(256)
return (red, green, blue)
}
You than access the values like that in your TapGestureRecognizer method:
var randomColors = randomColorCreatorV2()
var blueValue = randomColors.blue
Related
Apple recommends using system colors to adapt apps to light and dark mode automatically, for example:
myLabel.textColor = UIColor.secondaryLabel
Here Apple lists various properties to be used, such as the one in the example above, and system colors for background, placeholder text, and more.
But it doesn't list a property for UIButton elements.
Which property or other method should we use to adapt UIButtons to theme changes?
As of now, I'm doing this:
myButton.tintColor = UIColor.link
which is supposedly for links but is the only "clickable" property I found.
I'm not looking to use something like UIColor.systemRed, rather something like UIColor.systemBackground, which adapts automatically to the current theme.
I hope you create colored Assets not one by one. You can use this function to tint images as a extension of UIImageView. I also use the same technique for buttons.
func setImageAndColor(image: UIImage, color: UIColor) {
let templateImage = image.withRenderingMode(.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
In case you want to define all you own colors, I suggest to create a singleton class named Colors:
import UIKit
class Colors {
static let shared = Colors()
var statusBarStyle: UIStatusBarStyle = .lightContent
private init(){}
func setLightColors() {
statusBarStyle = .darkContent
yourColor = UIColor( // choose your favorite color
styleColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)//white
labelColor = UIColor(red: 15/255, green: 15/255, blue: 15/255, alpha: 1)
subLabelColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 1)
............ set values for all colors from here.
}
func setDarkColors() {
statusBarStyle = .lightContent
yourColor = // choose your favorite color
............
}
// set initial colors
var yourColor: UIColor =
}
If somebody is interested in the whole Colors class, text me or comment below.
I access the colors singleton by:
Colors.shared.yourColor
Also for first configuration I set in the very first VC the darkmode number (0-Auto; 1-On; 2-Off):
if darkmodeNumber == 0 {
if traitCollection.userInterfaceStyle == .light {
print("Light mode")
Colors.shared.setLightColors()
} else {
print("Dark mode")
Colors.shared.setDarkColors()
}
} else if darkmodeNumber == 1 {
Colors.shared.setDarkColors()
} else if modeNumber == 2 {
Colors.shared.setLightColors()
}
}
The statusbar should then change also the right way.
Use any system colors you like. They are all adaptive. I applied the system gray color to a button's text:
The color changes when we switch between light and dark mode.
I'm creating a simple Custom NSView that allows the user to input 3 text fields each for R,G and B values respectively. I already referenced this question and answer set here - it only accounts up to Swift 2.0. So, does anyone know the correct technique of obtaining this same effect in Swift 3.0? I can't seem to get anything that I'm doing to work. I keep getting errors of all sorts.
Here's the current technique I'm using (This seems to work... BUT it won't account for the other 2 RGB values, since it's used in the #IBAction):
//viewDidLoad
RVCustomView.wantsLayer = true
#IBAction func redValue(_ sender: AnyObject) {
print(red.stringValue)
var rValue = 0
let str = red.stringValue
if let n = NumberFormatter().number(from: str) {
rValue = Int(CGFloat(n))
}
CustomNSView.layer?.backgroundColor = CGColor(red: rValue, green: 255, blue: 255, alpha: 255)
}
If you want to dynamically change the background colour of a NSView each time the value of one of the three R, G, B text views changes, you could use the controlTextDidChange(notification:) delegate method of NSTextField coupled with outlets for each of the three text fields.
The method is fired every time one of the fields is changed and you use it for reading the value of the RGB fields (via outlets) and change the colour accordingly.
override func controlTextDidChange (notification: NSNotification?) {
// assuming the text fields' value is between 0 and 255
guard
let redValue = Float(redOutlet.stringValue),
let greenValue = Float(greenOutlet.stringValue),
let blueValue = Float(blueOutlet.stringValue)
else { return }
CustomNSView.layer?.backgroundColor = CGColor(red: CGFloat(redValue/255), green: CGFloat(greenValue/255), blue: CGFloat(blueValue/255), alpha: 255)
}
Note : don't forget to properly set the delegate for each of the three text fields!
I think you can just do that:
#IBAction func redValue(_ sender: AnyObject) {
yourView.backgroundColor = UIColor(colorLiteralRed: readValue/255, green: greenValue/255, blue: blueValue/255, alpha: 1)
}
I have three UIButtons and each has a different (UIColor) backgroundColor; for example, the backgroundColor of one UIButton is blue, one is pink, the other is orange. When I click each UIButton, I want to obtain the exact RGB (Red, Green, Blue) color values directly from it's backgroundColor property. (For example, if I clicked the UIButton with the pink backgroundColor, I will get a returned RGB values- R: 255, G: 0, B: 128.) Another way to explain this is, I want to convert a UIButton's UIColor backgroundColor into UIColor RGB values.
In Swift, what is the most simple, most efficient code to extract the RGB (Red, Green, Blue) color values of a UIButton's backgroundColor and then display the result in a UILabel?
Your task consists of three parts:
Obtaining the button that has been clicked from the click event handler
Given a UIButton obtain its background color, and
Given a UIColor obtain its RGB components
The first task is simple: add sender to the method that processes the click. The second task is also straightforward - all you need to do is accessing backgroundColor property. Finally, to get the components you need to call getRGB.
#IBAction func mainButton(button: UIButton) {
let bgColor:UIColor = button.backgroundColor!
var r : CGFloat = 0
var g : CGFloat = 0
var b : CGFloat = 0
var a: CGFloat = 0
if bgColor.getRed(&r, green: &g, blue: &b, alpha: &a) {
... r, g, b, and a represent the component values.
}
}
Note that it would be much simpler to do this the MVC way, i.e. by retrieving the components pre-stored in the model. Set your button tags to 0, 1, and 2, make a look-up table, and use it to perform the task:
let componentForTag: Int[][] = [[255, 0, 128], [128, 0, 0],[128, 128, 0]]
...
#IBAction func mainButton(button: UIButton) {
let components = componentForTag[button.tag]
// That's it! components array has the three components
}
I am trying to change the tab bar color in a view controller in XCode using swift. I have a hex that I matched up to an RGB value and I am trying to set that in this code. (Which does not work)
let color = UIColor(red: 41, green: 40, blue: 39, alpha: 1.0)
UITabBar.appearance().barTintColor = color
However this code does:
UITabBar.appearance().barTintColor = UIColor.whiteColor()
Can anyone explain why this doesn't work, and what I can do to fix it?
To use RGB values, just divide them by 255.0. This will produce a float value between 0 and 1.
let color = UIColor(red: 41.0/255.0, green: 40.0/255.0, blue: 39.0/255.0, alpha: 1.0)
It doesn't work because all of your RGB components are greater than 1, which is the maximum available value per-channel. You're probably thinking of the color channels as bytes, but that wouldn't scale to varying color bit depths. (For example, it was common to render to RGB565, not RGBA8888 in early versions of iOS. And you can probably expect Apple to make screens with 16-bit accuracy the norm, in the near future.) Floats from 0 to 1 are employed, to divorce the bit depth from the color representation.
https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIColor_Class/index.html#//apple_ref/occ/instm/UIColor/initWithRed:green:blue:alpha:
iOS 10 Swift 3.0
If you don't mind to use swift frameworks then us UINeraida to change Tabbar background as UIColor or HexColor or UIImage and change complete forground color.
For UITabBar
neraida.tabbar.background.color.uiColor(UIColor.orange, isTranslucent: false, viewController: self)
//change tab bar tint color //(select,unselect)
neraida.tabbar.foreground.color.uiColor((UIColor.white,UIColor.green), viewController: self)
//set Background Image for tab bar
neraida.tabbar.background.image("background", isTranslucent: false, viewController: self)
This way worked for me:
tabBarController?.tabBar.backgroundColor = .red
I've found a serious swift-bug in SpriteKit while working with SKSpriteNodes and their colors.
This code works fine on all iPhones beside the iPhone 5S:
var color1 = UIColor(red: 123/255, green: 123/255, blue: 123/255, alpha: 1)
var color2 = UIColor(red: 123/255, green: 123/255, blue: 123/255, alpha: 1)
var sprite = SKSpriteNode(color: color1, size: CGSizeMake(100, 100))
if(sprite.color == color2){
println("Same color")
}
As you see, the two colors are the absolut same. But on the iPhone 5S simulator, the if isn't called.
Has somebody else the same problem and can provide a solution?
According to the documentation here:
Sprite Kit works only with solid colors. For best results, use the
preset colors provided by the platform class or a custom color defined
in the RGBA device color space.
As a result somehow the SKSpriteNode has made some changes to the color parameter in the init function. You can see it if you call encode:
sprite.color.encode() // 140,646,370,382,768
color1.encode() // 140,646,367,110,928
If you use predefined color values, then your problem goes away:
var color3 = UIColor.blueColor()
var sprite3 = SKSpriteNode(color: color3, size: CGSizeMake(100, 100))
sprite3.color == color3 // true
You are comparing pointer values, not the actual color. Seeing that these are UIColor instances, you have to compare them using isEqual (showing ObjC code as I don't know what it looks like in Swift - or perhaps Swift is in fact using isEqual behind the scenes):
if ([sprite.color isEqual:color2])
If implemented correctly by UIColor this will compare the actual color values rather than the pointers.