textfield placeholder centered and also change color - ios

I want to make my UITextField placeholder to center aligned and also change the placeholderColor.
I have already make text center aligned using this ↓
extension String {
func attributedString(aligment: NSTextAlignment) -> NSAttributedString {
return NSAttributedString(text: self, aligment: aligment)
}
}
extension NSAttributedString {
convenience init(text: String, aligment: NSTextAlignment) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = aligment
self.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
}
}
and call above extension method like below
textField.attributedPlaceholder = NSAttributedString(text: text, aligment: .left)
But I am not able to change the color of placeholder. How should I change my placeholder color? Any help is appreciated.

Try using modified extension like below..
extension NSAttributedString
{
convenience init(text: String, aligment: NSTextAlignment, color:UIColor) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = aligment
self.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor:color])
}
}
Usage
textField.attributedPlaceholder = NSAttributedString(text: text, aligment: .left, color:UIColor.red)

Simply try this code
Swift 3.0
myTextField.textAlignment = .center
myTextField.attributedPlaceholder = NSAttributedString(string: "PlaceHolder", attributes: [NSForegroundColorAttributeName: UIColor.green])

Related

Make half of the TextView's text color Different than other 50% of the text SWIFT

I've got a large text in my UITextView and I want to make the 50% of the text's color red and the other 50% green . I've added NSMutableAttributedString in the TextView but it works's for the full range of the text . How to divide the textView's text into two sections and color them into red and green ?
let strNumber: NSString = self.text as NSString // TextView Text
let range = (strNumber).range(of: strNumber as String)
let attribute = NSMutableAttributedString.init(string: strNumber as String)
attribute.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14) , NSAttributedString.Key.foregroundColor : UIColor.red], range: range)
self.attributedText = attribute
It seems you have an extension to UITextView. The following extension function will make the existing attributed text of a text view be half red and half green. All other existing attributes, if any, will remain.
extension UITextView {
func makeHalfRedGreen() {
if let text = self.text {
let half = text.count / 2
let halfIndex = text.index(text.startIndex, offsetBy: half)
let firstRange = NSRange(..<halfIndex, in: text)
let secondRange = NSRange(halfIndex..., in: text)
let attrTxt = NSMutableAttributedString(attributedString: attributedText)
attrTxt.addAttribute(.foregroundColor, value: UIColor.red, range: firstRange)
attrTxt.addAttribute(.foregroundColor, value: UIColor.green, range: secondRange)
attributedText = attrTxt
}
}
}
Try to use function like below
text_lbl.attributedText = self.decorateText(txt1: "Red Color", txt2: “Blue Color”)
func decorateText(txt1:String, txt2:String)->NSAttributedString{
let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]
let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.blue, NSAttributedStringKey.font: UIFont(name: "Poppins-SemiBold", size: 14.0)!] as [NSAttributedStringKey : Any]
let textPartOne = NSMutableAttributedString(string: txt1, attributes: textAttributesOne)
let textPartTwo = NSMutableAttributedString(string: txt2, attributes: textAttributesTwo)
let textCombination = NSMutableAttributedString()
textCombination.append(textPartOne)
textCombination.append(textPartTwo)
return textCombination
}

How to change UIButton attributed text colour programatically?

I have a subclass (KeyButton) of UIButton where I am applying certain styles for the button. The following code adds the attributed text for buttons in the ViewController.
func superScriptText(text: String, button: KeyButton, fontSize: Int) {
let font:UIFont? = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.light)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:CGFloat(fontSize))
let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font:font!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:15], range: NSRange(location:1,length:1))
button.setAttributedTitle(attString, for: .normal)
}
How can I change the color of attributed text for the button in the class?
Just change:
let attString:NSMutableAttributedString =
NSMutableAttributedString(string: text, attributes: [.font:font!])
to:
let attString:NSMutableAttributedString =
NSMutableAttributedString(string: text, attributes: [.font:font!, .foregroundColor: UIColor.red])
NSAttributedStringKey.foregroundColor is used for the text color, see more options in docs.
You have to add the .foregroundColor key with a UIColor object as the value to the NSAttributedStrings attributes dictionary.
Example (assuming you have added a custom button in storyboard):
class CustomButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
let text = "CustomButton"
let font = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textColor = UIColor.orange
let attributes: [NSAttributedStringKey: Any] = [
.font: font,
.foregroundColor: textColor
]
let attributedText = NSAttributedString(string: text, attributes: attributes)
self.setAttributedTitle(attributedText, for: .normal)
}
}
I couldn't do this through UIButton subclass. I created the subclass of NSAttributtedText and add the following method:
var textColor: UIColor?
func setSuperScript(text: String, button: KeyButton, fontSize: Int) {
let font:UIFont? = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.light)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:CGFloat(fontSize))
let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font:font!, .foregroundColor: textColor!])
attString.setAttributes([.font:fontSuper!,.baselineOffset:15, .foregroundColor: textColor!,], range: NSRange(location:1,length:1))
button.setAttributedTitle(attString, for: .normal)
}
I am setting the color based on the logic I have and then set the attributed string color accordingly.

How to Increase Line spacing in UILabel in Swift

I have a label which has few lines of text and I want to increase the spacing between the lines. There are similar questions asked by others but the solutions don't solve my problems. Also my label may or may not contain paragraphs. I am new to Swift. Is there a solution using storyboard? Or only through NSAttributedString its possible?
Programatically add LineSpacing to your UILabel using following snippet.
Earlier Swift version
let attributedString = NSMutableAttributedString(string: "Your text")
// *** Create instance of `NSMutableParagraphStyle`
let paragraphStyle = NSMutableParagraphStyle()
// *** set LineSpacing property in points ***
paragraphStyle.lineSpacing = 2 // Whatever line spacing you want in points
// *** Apply attribute to string ***
attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// *** Set Attributed String to your label ***
label.attributedText = attributedString
Swift 4.0
let attributedString = NSMutableAttributedString(string: "Your text")
// *** Create instance of `NSMutableParagraphStyle`
let paragraphStyle = NSMutableParagraphStyle()
// *** set LineSpacing property in points ***
paragraphStyle.lineSpacing = 2 // Whatever line spacing you want in points
// *** Apply attribute to string ***
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// *** Set Attributed String to your label ***
label.attributedText = attributedString
Swift 4.2
let attributedString = NSMutableAttributedString(string: "Your text")
// *** Create instance of `NSMutableParagraphStyle`
let paragraphStyle = NSMutableParagraphStyle()
// *** set LineSpacing property in points ***
paragraphStyle.lineSpacing = 2 // Whatever line spacing you want in points
// *** Apply attribute to string ***
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// *** Set Attributed String to your label ***
label.attributedText = attributedString
From Interface Builder:
Programmatically:
SWift 4 & 4.2
Using label extension
extension UILabel {
func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {
guard let labelText = self.text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = lineHeightMultiple
let attributedString:NSMutableAttributedString
if let labelattributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// (Swift 4.2 and above) Line spacing attribute
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// (Swift 4.1 and 4.0) Line spacing attribute
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
Now call extension function
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) . // try values 1.0 to 5.0
// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0
Or using label instance (Just copy & execute this code to see result)
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
Swift 3
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
You can control the line spacing in storyboard.
Same question.
Recent solution for Swift 5.0
private extension UILabel {
// MARK: - spacingValue is spacing that you need
func addInterlineSpacing(spacingValue: CGFloat = 2) {
// MARK: - Check if there's any text
guard let textString = text else { return }
// MARK: - Create "NSMutableAttributedString" with your text
let attributedString = NSMutableAttributedString(string: textString)
// MARK: - Create instance of "NSMutableParagraphStyle"
let paragraphStyle = NSMutableParagraphStyle()
// MARK: - Actually adding spacing we need to ParagraphStyle
paragraphStyle.lineSpacing = spacingValue
// MARK: - Adding ParagraphStyle to your attributed String
attributedString.addAttribute(
.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: attributedString.length
))
// MARK: - Assign string that you've modified to current attributed Text
attributedText = attributedString
}
}
And the usage:
let yourLabel = UILabel()
let yourText = "Hello \n world \n !"
yourLabel.text = yourText
yourLabel.addInterlineSpacing(spacingValue: 1.5)
Swift 4 and Swift 5
extension NSAttributedString {
func withLineSpacing(_ spacing: CGFloat) -> NSAttributedString {
let attributedString = NSMutableAttributedString(attributedString: self)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.lineSpacing = spacing
attributedString.addAttribute(.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: string.count))
return NSAttributedString(attributedString: attributedString)
}
}
How to use
let example = NSAttributedString(string: "This is Line 1 \nLine 2 \nLine 3 ").withLineSpacing(15)
testLabel.attributedText = example
You can use this reusable extension:
extension String {
func lineSpaced(_ spacing: CGFloat) -> NSAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = spacing
let attributedString = NSAttributedString(string: self, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
return attributedString
}
}
Dipen's answer updated for Swift 4
let attr = NSMutableAttributedString(string: today)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2
attr.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attr.length))
label.attributedText = attr;
extension UILabel {
var spacing: CGFloat {
get {return 0}
set {
let textAlignment = self.textAlignment
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = newValue
let attributedString = NSAttributedString(string: self.text ?? "", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
self.attributedText = attributedString
self.textAlignment = textAlignment
}
}
}
let label = UILabel()
label.text = "test"
label.spacing = 10
//Swift 4:
func set(text:String,
inLabel:UILabel,
withLineSpacing:CGFloat,
alignment:NSTextAlignment){
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = withLineSpacing
let attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSAttributedStringKey.paragraphStyle,
value:paragraphStyle,
range:NSMakeRange(0, attrString.length))
inLabel.attributedText = attrString
inLabel.textAlignment = alignment
}
Create LabelStyle
struct LabelStyle {
let font: UIFont
let fontMetrics: UIFontMetrics?
let lineHeight: CGFloat?
let tracking: CGFloat
init(font: UIFont, fontMetrics: UIFontMetrics? = nil, lineHeight: CGFloat? = nil, tracking: CGFloat = 0) {
self.font = font
self.fontMetrics = fontMetrics
self.lineHeight = lineHeight
self.tracking = tracking
}
func attributes(for alignment: NSTextAlignment, lineBreakMode: NSLineBreakMode) -> [NSAttributedString.Key: Any] {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
paragraphStyle.lineBreakMode = lineBreakMode
var baselineOffset: CGFloat = .zero
if let lineHeight = lineHeight {
let lineHeightMultiple = lineHeight / font.lineHeight
paragraphStyle.lineHeightMultiple = lineHeightMultiple
baselineOffset = 1 / lineHeightMultiple
let scaledLineHeight: CGFloat = fontMetrics?.scaledValue(for: lineHeight) ?? lineHeight
paragraphStyle.minimumLineHeight = scaledLineHeight
paragraphStyle.maximumLineHeight = scaledLineHeight
}
return [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.kern: tracking,
NSAttributedString.Key.baselineOffset: baselineOffset,
NSAttributedString.Key.font: font
]
}
}
Create custom Label class and use our style
public class Label: UILabel {
var style: LabelStyle? { nil }
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory {
updateText()
}
}
convenience init(text: String?, textColor: UIColor) {
self.init()
self.text = text
self.textColor = textColor
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
updateText()
}
private func commonInit() {
font = style?.font
adjustsFontForContentSizeCategory = true
}
private func updateText() {
text = super.text
}
public override var text: String? {
get {
guard style?.attributes != nil else {
return super.text
}
return attributedText?.string
}
set {
guard let style = style else {
super.text = newValue
return
}
guard let newText = newValue else {
attributedText = nil
super.text = nil
return
}
let attributes = style.attributes(for: textAlignment, lineBreakMode: lineBreakMode)
attributedText = NSAttributedString(string: newText, attributes: attributes)
}
}
}
Create concrete Label
public final class TitleLabel {
override var style: LabelStyle? {
LabelStyle(
font: UIFont.Title(),
lineHeight: 26.21,
tracking: 0.14
)
}
}
and use it
#IBOutlet weak var titleLabel: TitleLabel!
In addition to using attributed strings & paragraph styles, for small adjustemnts, font descriptors can also come in handy.
For instance:
let font: UIFont = .init(
descriptor: UIFontDescriptor
.preferredFontDescriptor(withTextStyle: .body)
.withSymbolicTraits(.traitLooseLeading)!,
size: 0
)
This will create a font with a looser leading, resulting in a text with a slightly larger line height (it adds 2 points) than the default system font. traitTightLeading can also be used for the opposite effect (it reduces the leading of the font by 2 points).
I wrote a blog post comparing the approaches here: https://bootstragram.com/blog/line-height-with-uikit/.
This solution worked for swift 5
this is reference to answer of https://stackoverflow.com/a/62116213/13171606
I Made some changes for "NSMutableAttributedString" and included the full example, i think it will help u all
Note: Please Adjust Color and Font style if found any error.
Extension
extension NSAttributedString {
func withLineSpacing(_ spacing: CGFloat) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(attributedString: self)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.lineSpacing = spacing
attributedString.addAttribute(.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: string.count))
return NSMutableAttributedString(attributedString: attributedString)
}
}
Implementation Example
let myAttributedText = NSMutableAttributedString(string: "Please enter the required details to change your AAAAAAAAA AAAAA AAAAA. Maximum AAAAA can be AAA AA AAA AA.\n\nNote: If you do not have a AAAAA AAAA then please AAAAAAA us at 111-111-111 or send us an email AAAA AAAA AAA AAAAAAAAAA AAAAA address at xxxxxxxxxxxxxxxxxxxxxxxxxxxx.", attributes: [
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.gray,
.kern: 0.0]).withLineSpacing(8)
myAttributedText.addAttributes([
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.blue],
range: NSRange(location: 174, length: 11))
myAttributedText.addAttributes([
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.blue],
range: NSRange(location: 248, length: 28))
UILable
let myLabel: UILabel = {
let label = UILabel()
label.textAlignment = .left
label.numberOfLines = 0
label.attributedText = myAttributedText //Here is your Attributed String
return label
}()

How to change UITextfield placeholder color and fontsize using swift 2.0?

How to change UITextfield placeholder & fontsize in SWIFT 2.0?
#1. set Placeholder textfield color Programmatically
var myMutableStringTitle = NSMutableAttributedString()
let Name = "Enter Title" // PlaceHolderText
myMutableStringTitle = NSMutableAttributedString(string:Name, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 20.0)!]) // Font
myMutableStringTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count)) // Color
txtTitle.attributedPlaceholder = myMutableStringTitle
OR
txtTitle.attributedPlaceholder = NSAttributedString(string:"Enter Title", attributes: [NSForegroundColorAttributeName: yellowColor])
Note : Name is your placeholder of textField.
PlaceHolder TextFiled :
-------------------------------- OR -------------------------------------
#2. set Placeholder textfield color at runtime attribute
Set textfield placeHolder text Enter Title
Click on identity inspector of textfield property.
User Define Runtime Attributes, add color attributes
Key Path : _placeholderLabel.textColor
Type : Color
value : Your Color or RGB value
PlaceHolder TextFiled :
Updated for Swift 3
If you want to change the UITextField Placeholder color for Swift 3, use the following lines of code:
let yourTextFieldName = UITextField(frame: CGRect(x: 0, y: 0, width: 180, height: 21))
yourTextFieldName.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName: UIColor.white])
Updated for Swift 5
For swift 5.0 use NSAttributedString.Key.foregroundColor instead of NSForegroundColorAttributeName
So, do it like so
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
For swift 4 instead of
NSForegroundColorAttributeName
use
NSAttributedStringKey.foregroundColor
You can try with this sample code
let textFld = UITextField();
textFld.frame = CGRectMake(0,0, 200, 30)
textFld.center = self.view.center;
textFld.attributedPlaceholder = NSAttributedString(string:"Test Data for place holder", attributes:[NSForegroundColorAttributeName: UIColor.blueColor(),NSFontAttributeName :UIFont(name: "Arial", size: 10)!])
self.view.addSubview(textFld)
Placeholder for textfield Objective C
NSString* str = #"Placeholder text...";
NSRange range1 = [str rangeOfString:#"Placeholder text..."];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:str];
[attributedText setAttributes:#{
NSFontAttributeName:[UIFont fontWithName:customFont_NotoSans_Regular size:13.0]
}
range:range1];
[attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range1];
txtFld.font = [UIFont fontWithName:customFont_NotoSans_Regular size:13.0];
txtFld.keyboardType = UIKeyboardTypeDefault;
txtFld.attributedPlaceholder = attributedText;
It's easy to do with a subclass of UITextField.
Add placeholderColor property to easily set the color, and then observer changing of .placeholder to apply the color to it (with use of .attributedPlaceholder property)
var placeholderColor: UIColor = .lightGray
override var placeholder: String? {
didSet {
let attributes = [ NSAttributedString.Key.foregroundColor: placeholderColor ]
attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
}
}
You do need to set the placeholder text programatically for the color to apply.
set Textfield placeholder
let leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named:"ic_nav-bar_back.png"), landscapeImagePhone: nil, style: .plain, target: viewController, action: #selector(viewController.buttonClick(_:)))
leftBarButtonItem.imageInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
leftBarButtonItem.tintColor = UIColor(hex: 0xED6E19)
viewController.navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
A simple solution is override placeholder property in an UITextField extension. It will update color of placeholder whole project. You don't need to update your code in many places.
extension UITextField {
var placeholder: String? {
get {
attributedPlaceholder?.string
}
set {
guard let newValue = newValue else {
attributedPlaceholder = nil
return
}
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: Color.textFieldPlaceholder.color]
let attributedText = NSAttributedString(string: newValue, attributes: attributes)
attributedPlaceholder = attributedText
}
}
}
open your identity inspector by selecting text field and then put " placeholderLabel.textColor " in key path by pressing + button .
Give the type " Color " and in value select desired RGB color.
Swift 5
textfiled.attributedPlaceholder = NSAttributedString(string:NSLocalizedString("Input Group Name", comment: "Input Group Name"), attributes: [NSAttributedString.Key.foregroundColor: yourColor.withAlphaComponent(0.5)])

UILabel with two different color text

How can i have a UILabel with two different colors for the font? I will have text in two different strings and i want to make text with first string as red and second as green. The length of both the string is variable.
Try TTTAttributedLabel. It's a subclass of UILabel that supports NSAttributedStrings, which would make it easy to have multiple colors, fonts, and styles in the same string.
Edit: Alternatively, if you don't want the 3rd party dependency and are targeting iOS 6, UILabel now has the attributedText property.
You can't do this within a UILabels. But my suggestion is that instead of using multiple UILabel just concentrate on NSAttributedString. Find UIControllers that draw NSAttributedString because UILabel, UITextView do not support NSAttributedString.
PS: if you plan to distribute an iOS6 or later application, as UILabel now support NSAttributedString, you should use UILabel directly instead of OHAttributedLabel as it is now natively supported by the OS.
UILabel can only have one color. You either need a more sophisticated element, or - probably easier - just use two separate labels. Use [yourLabel sizeToFit]; and place them accordingly.
Swift 4
(Note: notation for attributed string key is changed in swift 4)
Here is an extension for NSMutableAttributedString, that add/set color on string/text.
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
Now, try above extension with UILabel and see result
let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let red = "red"
let blue = "blue"
let green = "green"
let stringValue = "\(red)\n\(blue)\n&\n\(green)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: red) // or use direct value for text "red"
attributedString.setColor(color: UIColor.blue, forText: blue) // or use direct value for text "blue"
attributedString.setColor(color: UIColor.green, forText: green) // or use direct value for text "green"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
Here is solution in Swift 3:
extension NSMutableAttributedString {
func setColorForText(textToFind: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
if range != nil {
self.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
}
}
func multicolorTextLabel() {
var string: NSMutableAttributedString = NSMutableAttributedString(string: "red\nblue\n&\ngreen")
string.setColorForText(textToFind: "red", withColor: UIColor.red)
string.setColorForText(textToFind: "blue", withColor: UIColor.blue)
string.setColorForText(textToFind: "green", withColor: UIColor.green)
labelObject.attributedText = string
}
Result:
In iOS 6 UILabel has NSAttributedString property. So use that.

Resources