Nsattributedstring in Swift

Source: Internet
Author: User

Reprinted from: https://www.invasivecode.com/weblog/attributed-text-swift/

I have been talking quite a lot in the past about what to customize text in your apps to improve the UI of your applications . Before IOS 6, Core Text is the only available option for developers. Although a great framework, Core Text is not a very straightforward tool to use. You can check our Core Text tutorial in objective-c here. In IOS 6, Apple introduced NSAttributedString . You can check a couple of posts on this topic here and here.

Core Text still remains the go for some specific cases that we'll see later NSAttributedString but brings less hassle so, if PO Ssible, you should adopt it as a your first option. Then, on early June, Apple introduced Swift. In this tutorial, we'll build a project using Swift and NSAttributedString .

First, let me tell you more about some Cocoa classes this give you easy access to text customization. NSAttributedStringallows you to customize the text attributes of UILabel , UIButton , UIPickerView , and UITableViewCell .

To use these properties, you just has to add any object of type UILabel , UIButton UIPickerView or to UITableViewCell your project and assign an NSAttributedString. For example, for a UILabel object, you would do the following:

labelName.attributedText = attributedString
Let ' s build a example

Let's write some code to see how to create attributed strings using Swift.

Launch Xcode and create a new Single-view application project. Name it attributedstringexample. Open the Viewcontroller.swift file and edit the viewDidLoad() method as follows:

  override func Viewdidload () {super.viewdidload () if Let Titlefont = Uifont (name: "Copperplate", size:50  .0) {Let Shadow:nsshadow = Nsshadow () Shadow.shadowoffset = Cgsizemake ( -2.0, -2.0) let attributes = [Nsfontattributename:titlefont, nsunderlinestyleattributename:1, Nsforegroundcolorattributena Me:UIColor.whiteColor (), Nstexteffectattributename:nstexteffectletterpressstyle, Nsstrokewidthattribute name:3.0, Nsshadowattributename:shadow] var title = nsattributedstring (string: "Nsattributedstring", att ributes:attributes)//1 var label = UILabel (((Self.view.bounds.size.width-title.size (). width) /2.0), 40.0, Title.size (). Width, title.size (). Height))//2 label.attributedtext = title//3 View.addsubview (label)//4}}  

Here, we create the attributed string with the attributes on line 1. In this particular case, we set the font and the size, text effect, color, shadow and underline attribute.

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. Now, just build and run and your should see the following result:

This example shows how to create an attributed string and how to assign it to the property from attributedText a UILabel . Easy, right? But could you wonder, which attributes can I apply? Let's check them out, one by one.

Character Attributes

Let's check the character attributes currently available that's can apply to your text:

Nsfontattributename

This allows the font of your text. If not specified otherwise, the default is 12-point Helvetica (Neue).

Nsparagraphstyleattributename

This allows your to apply multiple attributes (such as alignment, Tab stops and line break mode) to a range of text (aka PA Ragraph).

Nsforegroundcolorattributename

The color of the text during rendering (black, by default).
The image below shows an example with red foreground.

Nsbackgroundcolorattributename

The color of the background area behind the text (no color, by default). Here, a example with yellow background in the image below.

Nsligatureattributename

ligatures cause specific character combinations to being rendered using a single custom glyph so corresponds to those Chara Cters. The default value is 1, indicating the use of ligatures. You can specify no ligatures with value 0.
The following image shows the difference between setting a text with ligature attribute 0 (top text) and 1 (bottom text). Pay attention to the FF in Caffeteria, the ffi in ufficiale and the FFL in affluente. They all belong to the F-ligatures type and they solve the unatractive collision between elements of the neighboring Chara Cters (The hook and crossbar of a double f or the hook of the The F and the dot of the i).

Nskernattributename

KERN Specifies the space between specific characters and it ' s font-dependent. The default value is 0, which means no kerning. Any other number would specify the number of points between characters.

The following image shows the difference between setting a text with Kern attribute value ten (top text) and 0 (bottom text).

Nsstrikethroughstyleattributename

The value of this attribute indicates wether the text was crossed out (strikethrough). The Default value is none and you can specify several values to cross the text with different styles.
The following example shows the result of applying different values of this property.

Nsunderlinestyleattributename

The value of this attribute indicates wether the text was rendered with a line under. The default value is None and you can specify different values of underlining matching the same styles as for the Striket Hrough style.

Nsstrokecolorattributename

This uicolor describes the outline color of the text. The default value is the same uicolor defined as the text foreground.

Nsstrokewidthattributename

This value represent the amount to the stroke width. By default are 0, for no additional changes. A positive value would change the stroke width alone, a negative value would stroke and fill the text.

Find A example in the image below.

Nsshadowattributename

This attribute allows the add shadow to your text. Default value is nil, which mean, no shadow. Find A example in the image below.

Nstexteffectattributename

Use the attribute to specify a text effect. By default, the value of this property is nil, indicating no text effect.

Nsattachmentattributename

The value of this attribute was an Nstextattachment object. The default value of the is nil, indicating no attachment.

Nslinkattributename

The value of this attribute was an nsurl or and NSString object. The default value of the is nil, indicating no link.

Nsbaselineoffsetattributename

This attribute indicates the character's offset from the baseline, expressed in points. The baseline is the imaginary line upon which a line of text rests. The default value is 0.
The baseline for the text below are the red line.

Nsunderlinecolorattributename

This attribute indicates the color of the line underneath the text. The default value coincides with the foreground color.
Find A example with a green double line in the image below.

Nsstrikethroughcolorattributename

This indicates the color of the attribute. The default value is the same as the foreground color.
Find A example with a red line in the image below.

Nsobliquenessattributename

This attribute indicates the skew to being applied to glyphs. The default value is 0, meaning no skew. A positive value would lean the text towards the right, a negative value would lean it towards the left.
This attribute allows-to-create your own italic version for a typeface that doesn ' t has one. However, before you create your own, think if there might is a reason why the font doesn ' t has the oblique version. Find An example using the ' Academy engraved let ' using a skew value of 1.

Nsexpansionattributename

This attribute indicates the logs of the expansion factor to being applied to glyphs. Default value is 0, no expansion. Use a positive value to enlarge and a negative value to shrink the text.
The following image shows the difference between setting a text with expansion factor 0 (text at the top) and 1 (text at the bottom).

Nswritingdirectionattributename

This attribute can help you write the text from the Left-to-right and from Right-to-left. You can also embed text in a text with a different writing direction and override the inherent directionality of character S.

Nsverticalglyphformattributename

This attribute indicates with the value 0 horizontal text and with value 1 vertical text. In IOS, horizontal text was always used and specifying a different value is undefined. That means, should not being using this attribute in IOS.

These is all the attributes offered by Apple, can apply to the text in your apps. You can add or remove attributes to a particular range of characters using NSMutableAttributedString combining chunks of text with different at Tributes. Here's an example combining different styles:

nsattributedstring Limitations

There is a couple of things that I ' m aware of that is still not possible to does with attributed strings:

    1. If you need-to-render text vertically, attributed strings don ' t seem to offer this solution just yet.
    2. If you want-to-draw into a-shape other than a rectangle, you'll still have the use Core Text.
    3. If you want to render your text on a non-horizontal line (such as a curved line), you'll probably has to pick either or a CATextLayer .

However, Apple is adding + and more attributes to make it easier for us to render text and I ' m happy to share with you All those improvements. I hope you found this post useful!

Happy coding!

Eva

Eva Diaz-santana (@evdiasan) is cofounder of Invasivecode. She develops iOS applications andteaches iOS development since 2008. She worked at Apple as Cocoa Architect and UX Designer.

Nsattributedstring in Swift

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.