How do you change the color of a UIFont?
Solution 1
UIFont does not contain/maintain any color information, so this is not possible. In general, controls that use UIFont such as a UILabel have both a font and a textColor property. So you would set a label's font and it's color like this:
myLabel.textColor = [UIColor blackColor];
myLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:8.0];
Solution 2
If you are drawing text you can use following function;
[text drawAtPoint:CGPointMake(x, y) withAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:sizeOfFont], NSForegroundColorAttributeName:[UIColor redColor] }];
Solution 3
If by any chance you're rendering the font to a texture in OpenGL, you can also use the CGContext* functions,
Assuming you already have a valid cgcontext:
CGContextSelectFont(cgContext, "Arial", 24, kCGEncodingMacRoman);
CGContextSetRGBStrokeColor(cgContext, 1.0f, 1, 1, .5f) ;
CGContextShowTextAtPoint(cgContext, 20, 20, "HI THERE", strlen("HI THERE") ) ;
Solution 4
You can also use [myLabel setTextColor:[UIColor grayColor]];
.
CodeGuy
Updated on August 21, 2022Comments
-
CodeGuy almost 2 years
I've searched the web and I can't get a good answer, although I'm sure this is very simple. Can someone please show me how to do the following: Make a UIFont of name "Helvetica-Bold", size 8.0, and color of black.
I've got the name and size, but I can't figure out how to change the color:
UIFont *textFont = [UIFont fontWithName:@"Helvetica-Bold" size:8.0];
Thanks!
-
iosMentalist almost 11 yearsthis functionality is removed from IOS 6.0
-
iosMentalist almost 11 yearsthis functionality is removed from IOS 6.0
-
MarkAurelius over 7 yearsI think it works. I just did this in swift to get an alternating font colour for a UILabel: commandCount += 1 label.textColor = [.white, .black][commandCount % 2]
-
Hibbem over 6 yearsNote that CGContextSelectFont is deprecated now, use the CoreText API instead.