Swift 4 Label attributes

Swift 4 Label attributes

nsattributedstring alignment swift 4
nsattributedstring add attribute
change font of attributed string swift
nsattributedstring -- swift 4 example
nsattributedstring font swift 4
bold non bold text in a single uilabel
nsmutableattributedstring objective-c
uilabel with different font sizes swift

I'm moving from swift 3 to swift 4. I have UILabels that I am giving very specific text properties to the label. I'm getting an 'unexpectedly found nil while unwrapping optional value' error when strokeTextAttributes is being initialized. I'm totally lost to be frank.

In swift 3 the of strokeTextAttributes was [String : Any] but swift 4 threw errors until I changed it to what it is below.

let strokeTextAttributes = [
    NSAttributedStringKey.strokeColor.rawValue : UIColor.black,
    NSAttributedStringKey.foregroundColor : UIColor.white,
    NSAttributedStringKey.strokeWidth : -2.0,
    NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
    ] as! [NSAttributedStringKey : Any]


chevronRightLabel.attributedText = NSMutableAttributedString(string: "0", attributes: strokeTextAttributes)

@Larme's comment about the .rawValue not being needed is correct.

Also, you can avoid the force cast that crashes your code using explicit typing:

let strokeTextAttributes: [NSAttributedString.Key: Any] = [
    .strokeColor : UIColor.black,
    .foregroundColor : UIColor.white,
    .strokeWidth : -2.0,
    .font : UIFont.boldSystemFont(ofSize: 18)
]

This gets rid of the repetitive NSAttributedString.Key., too.

UILabel, Make Custom label for the OutLine effect. let strokeTextAttributes = [ NSAttributedString.Key.strokeColor : UIColor.red, NSAttributedString.Key.​foregroundColor  Swift provides the following Interface Builder attributes: IBAction, IBSegueAction, IBOutlet, IBDesignable, and IBInspectable. These attributes are conceptually the same as their Objective-C counterparts. You apply the IBOutlet and IBInspectable attributes to property declarations of a class.


In Swift 4.0+, attributed string accepts json (dictionary) with key type NSAttributedStringKey or NSAttributedString.Key.

So you must change it from [String : Any] to

Swift 4.1 & below - [NSAttributedStringKey : Any] & Swift 4.2 & above - [NSAttributedString.Key : Any]

Swift 4.2

Initialiser for AttributedString in Swift 4.2 is changed to [NSAttributedString.Key : Any]?

public init(string str: String, attributes attrs: [NSAttributedString.Key : Any]? = nil)

Here is sample working code.

let label = UILabel()
let labelText = "String Text"

let strokeTextAttributes = [
     NSAttributedString.Key.strokeColor : UIColor.black,
     NSAttributedString.Key.foregroundColor : UIColor.white,
     NSAttributedString.Key.strokeWidth : -2.0,
     NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)
   ] as [NSAttributedString.Key : Any]

label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)
Swift 4.0

Initialiser for AttributedString in Swift 4.0 is changed to [NSAttributedStringKey : Any]?.

public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil)

Here is sample working code.

let label = UILabel()
let labelText = "String Text"

let strokeTextAttributes = [
     NSAttributedStringKey.strokeColor : UIColor.black,
     NSAttributedStringKey.foregroundColor : UIColor.white,
     NSAttributedStringKey.strokeWidth : -2.0,
     NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
   ] as [NSAttributedStringKey : Any]

label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)

Look at this Apple Document, for more info: NSAttributedString - Creating an NSAttributedString Object

Custom Label Effects in Swift 5.1 - Anand Nimje, Key.font: font] let attributedQuote = NSAttributedString(string: quote, attributes: attributes). Now we're asking for the same text to be rendered in  Add one label and three buttons looking like this: Open the assistant editor, set to Automatic so the ViewController.swift file appears. Control-drag from the label to the code in the ViewController class. Make an outlet called myLabel. Drag from the ChalkDuster button to the code. Make an action named myFontButton.


NSAttributedStringKey.strokeColor.rawValue is of type String

NSAttributedStringKey.strokeColor is of type NSAttributedStringKey

So its unable to convert String to NSAttributedStringKey. You have to use like below:

let strokeTextAttributes: [NSAttributedStringKey : Any] = [
    NSAttributedStringKey.strokeColor : UIColor.black,
    NSAttributedStringKey.foregroundColor : UIColor.white,
    NSAttributedStringKey.strokeWidth : -2.0,
    NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
]

NSAttributedString by example – Hacking with Swift, In this tutorial we will assign a set of attributes to each word of the text inside a label. This tutorial is made with Xcode 10 and built for iOS 12. Swift has three loop statements: a for - in statement, a while statement, and a repeat - while statement. Control flow in a loop statement can be changed by a break statement and a continue statement and is discussed in Break Statement and Continue Statement below.


Swift 4 Attributed text with multiple colors

extension NSMutableAttributedString 
{
@discardableResult func DustyOrange(_ text: String, Fontsize : CGFloat) -> NSMutableAttributedString 
{
    let attrs: [NSAttributedStringKey: Any] = [.font: UIFont(name: "SFUIDisplay-Regular", size: Fontsize)!, NSAttributedStringKey.foregroundColor: UIColor(red: 242.0/255.0, green: 97.0/255.0, blue: 0.0/255.0, alpha: 1.0) ]
    let boldString = NSMutableAttributedString(string:text, attributes: attrs)
    append(boldString)
    return self
}
@discardableResult func WarmGrey(_ text: String, Fontsize : CGFloat) -> NSMutableAttributedString {
    let attrs: [NSAttributedStringKey: Any] = [.font: UIFont(name: "SFUIDisplay-Regular", size: Fontsize)!, NSAttributedStringKey.foregroundColor: UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1.0) ]
    let boldString = NSMutableAttributedString(string:text, attributes: attrs)
    append(boldString)
    return self
}
}

Now you can Execute the function something like this to use as a globally

func FormattedString(Orange : String, WarmGrey : String ,fontsize : CGFloat) -> NSMutableAttributedString 
{
   let paragraphStyle = NSMutableParagraphStyle()
   paragraphStyle.alignment = .left
   paragraphStyle.lineSpacing = 1
   paragraphStyle.paragraphSpacing = 1
   let formattedString = NSMutableAttributedString()
   formattedString
    .DustyOrange(Orange, Fontsize: fontsize)
    .WarmGrey(WarmGrey, Fontsize: fontsize )
  formattedString.addAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: formattedString.length))
   return formattedString
}

You can use globalized function like this

 yourLabelName.attributedText = FormattedString(Orange: "String with orange color", WarmGrey: " String with warm grey color.", fontsize: 11.5)

Attributed text with image

func AttributedTextwithImgaeSuffix(AttributeImage : UIImage , AttributedText : String , buttonBound : UIButton) -> NSMutableAttributedString 
 {
   let fullString = NSMutableAttributedString(string: AttributedText + "  ")
   let image1Attachment = NSTextAttachment()
   image1Attachment.bounds = CGRect(x: 0, y: ((buttonBound.titleLabel?.font.capHeight)! - 
  AttributeImage.size.height).rounded() / 2, width: 
  AttributeImage.size.width, height: AttributeImage.size.height)
  image1Attachment.image = AttributeImage
  let image1String = NSAttributedString(attachment: image1Attachment)
  fullString.append(image1String)
  fullString.append(NSAttributedString(string: ""))
  return fullString 
}

you can use "NSTextAttachment" with your button label like this.

   yourUIButton.setAttributedTitle(AttributedTextwithImgaeSuffix(AttributeImage: desiredImage, AttributedText: "desired UIButton title", buttonBound: yourUIButton), for: .normal)

Attributed Strings iOS Tutorial, Learn how to build Make School Notes in Swift 4 Let's start with the top label. In Main.storyboard , set the following attributes for the top (note title) label:. The third attribute uses NSStrokeWidthAttributeName to set a stroke width of 4 points, giving us an outlined letter. Build and run this: Build and run this: Character Background Change


In Swift 4.x, this should look like :

        let strokeTextAttributes: [NSAttributedStringKey: Any] = [
        NSStrokeColorAttributeName: UIColor.black,
        NSForegroundColorAttributeName : UIColor.white,
        NSStrokeWidthAttributeName : -2.0,
        NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)
    ]

Creating Custom Table View Cells, A drop-in replacement for UILabel that supports attributes, data detectors, links, and Even though UILabel received support for NSAttributedString in iOS 6, Label style inheritance for attributed strings; Custom styling for links within the  Add and customize labels in your interface programmatically or with the Attributes inspector in Interface Builder. Follow these steps to add a label to your interface: Supply either a string or an attributed string that represents the content. If you are using a nonattributed string, configure the appearance of the label.


TTTAttributedLabel/TTTAttributedLabel: A drop-in , A text field with an animated floating label and other Material Design features. Material iOS text fields consist of both single-line and multi-line offerings in both filled and outlined styles. The single-line text Helper/error/counter text attributes​  It seems easy to create a link on a label in a Swift iOS App. NSAttributedString: is a piece of text that has attributes (like links or fonts) that apply to portions of text.


Text Fields, It uses Swift to change a Label's text and write to the screen. This is automatically generated by Xcode for your program. The UILabel has a text property. Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here.


Swift UILabel Tutorial: iPhone App, Uses ViewController, Only use this example, if you are sure, that you don't want to use a UIButton for some reason. Create label; Enable user interaction; Add UITapGestureRecognizer. Line 2 instantiates a label and Line 3 sets the attributed string to the label. Finally (Line 4), we add the label as a subview of the viewcontroller view. I also changed to blue the background color of the view from the attributes Inspector in Interface Builder.