Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set textColor of UILabel in Swift

When I try setting the color of a UILabel to the color of another UILabel using the code

myLabel.textColor = otherLabel.textColor 

It doesn't change the color. When I use this code, however,

myLabel.textColor = UIColor.redColor() 

It changes the color correctly. What's the issue with the first line?

like image 446
kag359six Avatar asked Sep 14 '14 19:09

kag359six


People also ask

How do you change the color of a label in Xcode?

When you click the color box in the UI you will see it get selected. If you don't see it get selected, click it again. It's when it doesn't get selected that the colour changes the background instead (which seems to be the default selection if you keep the color picker open).


Video Answer


2 Answers

The easiest workaround is create dummy labels in IB, give them the text the color you like and set to hidden. You can then reference this color in your code to set your label to the desired color.

yourLabel.textColor = hiddenLabel.textColor 

The only way I could change the text color programmatically was by using the standard colors, UIColor.white, UIColor.green...

like image 101
Piet Grootnoten Avatar answered Oct 04 '22 00:10

Piet Grootnoten


This code example that follows shows a basic UILabel configuration.

let lbl = UILabel(frame: CGRectMake(0, 0, 300, 200)) lbl.text = "yourString"  // Enum type, two variations: lbl.textAlignment = NSTextAlignment.Right lbl.textAlignment = .Right  lbl.textColor = UIColor.red lbl.shadowColor = UIColor.black lbl.font = UIFont(name: "HelveticaNeue", size: CGFloat(22)) self.view.addSubview(lbl) 
like image 24
Mayank Patel Avatar answered Oct 04 '22 00:10

Mayank Patel