I am trying to set the textColor
of a UITextView
by assigning it a value.
Earlier in the program I have
textView.textColor
as par you submited answer this is not an answer UIColorFromRGB
is a Macro that define above at @implementation
like
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0];
Then you can use like
textView.textColor = UIColorFromRGB(0x888888);
you can use its property of UIColor
for setting color of text bg-color etc in objective c
You can do this by following these steps:
Do convert hex value to RGB use HexToRGB.
And then change the text color of your textview by doing this :
textview.textColor = [UIColor colorWithRed:244/255.00f
green:133/255.00f blue:116/255.00f alpha:1.0f]; // values are just an example
I figured out you can use UIColorFromRGB()
to convert it to a UIColor.
e.g.
textView.textColor = UIColorFromRGB(0x888888);
Swift extension version
public extension UIColor {
public convenience init<T>(rgbValue: T, alpha: CGFloat = 1) where T: BinaryInteger {
guard rgbValue > 0 else {
self.init(red: 0, green: 0, blue: 0, alpha: alpha)
return
}
guard rgbValue < 0xFFFFFF else {
self.init(red: 1, green: 1, blue: 1, alpha: alpha)
return
}
let r: CGFloat = CGFloat(((rgbValue & 0xFF0000) >> 16) / 0xFF)
let g: CGFloat = CGFloat((rgbValue & 0x00FF00) >> 8 / 0xFF)
let b: CGFloat = CGFloat((rgbValue & 0x0000FF) / 0xFF)
self.init(red: r, green: g, blue: b, alpha: alpha)
}
}
usage:
let white = UIColor(rgbValue: 16777215)
let red = UIColor(rgbValue: 16711680)
let green = UIColor(rgbValue: 0x00FF00)
let blue = UIColor(rgbValue: 0x0000FF)
let yellow = UIColor(rgbValue: 0xFFFF00)
let black = UIColor(rgbValue: 0)
You can use the following function to convert a RGB hexadecimal color Int
to a UIColor
.
func uiColorFromHex(rgbValue: Int) -> UIColor {
// & binary AND operator to zero out other color values
// >> bitwise right shift operator
// Divide by 0xFF because UIColor takes CGFloats between 0.0 and 1.0
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 0xFF
let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 0xFF
let blue = CGFloat(rgbValue & 0x0000FF) / 0xFF
let alpha = CGFloat(1.0)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
And can be used like this
let myColorValue = 0x888888
let color = uiColorFromHex(myColorValue)
it was necessary to use
textView.textColor = [UIColor colorWithRed:<#(CGFloat)#> green:<#(CGFloat)#> blue:<#(CGFloat)#> alpha:<#(CGFloat)#>];
try it:
- (UIColor *)UIColorFromRGB:(NSInteger)rgbValue {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
green:((float)((rgbValue & 0xFF00) >> 8))/255.0
blue:((float)(rgbValue & 0xFF))/255.0
alpha:1.0];
}
...
textView.textColor = [self UIColorFromRGB:0x888888];