NSAttributedString in Swift

I have been talking quite a lot in the past about how to customize text in your app to improve the UI of your applications. Before iOS 6, Core Text was 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 about this topic here and here.
Core Text still remains the way to go for some specific cases that we will see later butNSAttributedString brings less hassle so, if possible, you should adopt it as a your first option. Then, on early June 2014, Apple introduced Swift. In this tutorial, we will build a project using Swift and NSAttributedString.
First, let me tell you more about some Cocoa classes that give you easy access to text customization. NSAttributedString allows you to customize the text attributes ofUILabel, UIButton, UIPickerView, and UITableViewCell.
To use these properties, you just have to add any object of type UILabel, UIButton,UIPickerView or UITableViewCell to your project and assign anNSAttributedString. For example, for a UILabel object, you would do the following:
labelName.attributedText = attributedString
Let’s build an 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,
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
NSStrokeWidthAttributeName : 3.0,
NSShadowAttributeName : shadow]
var title = NSAttributedString(string: "NSAttributedString", attributes: attributes) //1
var label = UILabel(frame: CGRectMake(((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 in 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 you should see the following result:
This example shows how to create an attributed string and how to assign it to theattributedText property from a UILabel. Easy, right? But you may 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 you can apply to your text:
NSFontAttributeName
This allows you to change the font of your text. If not specified otherwise, default is 12-point Helvetica(Neue).
NSParagraphStyleAttributeName
This allows you to apply multiple attributes (such as alignment, tab stops and line break mode) to a range of text (aka paragraph).
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, an example with yellow background in the image below.
NSLigatureAttributeName
Ligatures cause specific character combinations to be rendered using a single custom glyph that corresponds to those characters. 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 characters (the hook and crossbar of a double f or the hook of 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 will specify the number of points between characters.
The following image shows the difference between setting a text with kern attribute value 10 (top text) and 0 (bottom text).
NSStrikethroughStyleAttributeName
The value of this attribute indicates wether the text is crossed out (strikethrough). Default value is none but you can specify several values to cross out 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 is rendered with a line under. The default value is none, but you can specify different values of underlining matching the same styles as for the strikethrough 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 change the stroke width. By default is 0, for no additional changes. A positive value will change the stroke width alone, a negative value will stroke and fill the text.
Find an example in the image below.
NSShadowAttributeName
This attribute allows you to add shadow to your text. Default value is nil, which mean, no shadow. Find an example in the image below.
NSTextEffectAttributeName
Use this 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 is an NSTextAttachment object. The default value of this property is nil, indicating no attachment.
NSLinkAttributeName
The value of this attribute is an NSURL or and NSString object. The default value of this property 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 is the red line.
NSUnderlineColorAttributeName
This attribute indicates the color of the line underneath the text. The default value coincides with the foreground color.
Find an example with a green double line in the image below.
NSStrikethroughColorAttributeName
This attribute indicates the color of the cross out line. The default value is the same as the foreground color.
Find an example with a red line in the image below.
NSObliquenessAttributeName
This attribute indicates the skew to be applied to glyphs. The default value is 0, meaning no skew. A positive value will lean the text towards the right, a negative value will lean it towards the left.
This attribute allows you to create your own italic version for a typeface that doesn’t have one. However, before you create your own, think if there might be a reason why the font doesn’t have the oblique version. Find an example using ‘Academy Engraved LET’ using a skew value of 1.
NSExpansionAttributeName
This attribute indicates the log of the expansion factor to be 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 text from 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 characters.
NSVerticalGlyphFormAttributeName
This attribute indicates with value 0 horizontal text and with value 1 vertical text. In iOS, horizontal text is always used and specifying a different value is undefined. That means that you should not be using this attribute in iOS.
These are all the attributes offered by Apple that you can apply to the text in your apps. You can add or remove attributes to a particular range of characters usingNSMutableAttributedString combining chunks of text with different attributes. Here an example combining different styles:
NSAttributedString limitations
There are a couple of things that I’m aware of that are still not possible to do with attributed strings:
- If you need to render text vertically, attributed strings don’t seem to offer this solution just yet.
- If you want to draw into a shape other than a rectangle, you will still have to use Core Text.
- If you want to render your text on a non-horizontal line (such as a curved line), you will probably have to pick either
Core Textor aCATextLayer.
However, Apple is adding more 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.


示例:
private func getAttributeString(stringContent: String?, stringLabel: String?) -> NSMutableAttributedString {
let string = stringLabel! + stringContent!
let style = NSMutableParagraphStyle()
style.alignment = .Center
style.lineSpacing = 11
let attributes = [
NSFontAttributeName: UIFont.systemFontOfSize(15),
NSParagraphStyleAttributeName: style
]
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
attributedString.setAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(15)], range: NSMakeRange(0, stringLabel!.characters.count))
return attributedString
}
private func applyWholeStringParagraphStyle(attributedStringTemp: NSMutableAttributedString) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10.5
attributedStringTemp.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedStringTemp.length-1))
}
NSAttributedString in Swift的更多相关文章
- Swift NSAttributedString的使用
NSMutableAttributedString let testAttributes = [NSAttributedStringKey.foregroundColor: UIColor.blue, ...
- swift系统学习控件篇:UIbutton+UIlabel+UITextField+UISwitch+UISlider
工作之余,学习下swift大法.把自己的学习过程分享一下.当中的布局很乱,就表在意这些细节了.直接上代码: UIButton+UILabel // // ViewController.swift // ...
- iOS 下拉刷新和加载更多 (OC\Swift)
Swift语言出来之后, 可能还没有第三方的下拉刷新和上提加载, 所以自己用UIRefreshControl控件和UITableView实例的tableFooterView(底部视图)属性结合起来写了 ...
- iOS开发——实战篇Swift篇&UItableView结合网络请求,多线程,数据解析,MVC实战
UItableView结合网络请求,多线程,数据解析,MVC实战 学了这么久的swift都没有做过什么东西,今天就以自己的一个小小的联系,讲一下,怎么使用swift在实战中应用MVC,并且结合后面的高 ...
- 使用OC和swift创建系统自带的刷新界面
使用OC和swift创建系统自带的刷新界面 一:swift刷新界面代码: import UIKit class ViewController: UITableViewController { // 用 ...
- 转:【iOS开发每日小笔记(十一)】iOS8更新留下的“坑” NSAttributedString设置下划线 NSUnderlineStyleAttributeName 属性必须为NSNumber
http://www.bubuko.com/infodetail-382485.html 标签:des class style 代码 html 使用 问题 文件 数据 ...
- Swift 使用Extension 场景 浅析
别人一看到我的 Swift 代码,立刻就会问我为什么如此频繁的使用 extension.这是前几天在我写的另一篇文章中收到的评论: 我大量使用 extension 的主要目的是为了提高代码可读性.以下 ...
- swift常用第三方库
网络 Alamofire:http网络请求事件处理的框架. Moya:这是一个基于Alamofire的更高层网络请求封装抽象层. Reachability.swift:用来检查应用当前的网络连接状况. ...
- swift UIAlertController使用 UIAlertController的宽度 为270
添加子控件 1. 有标题, alert标题高度大概 是 40, 子控件的 Y一般在40 ,如果中间有换行, \n 的高度大概是30 2.alert的宽度 是270, 设置frame 的时候注意 /// ...
随机推荐
- 不创建类将json数据转换
一般,取到json数据之后,都会将json数据转换为对象,通过属性取得里面的属性值,这样做可以很好地利用vs的智能提示,让开发更轻松,但是代价就是,你需要手动的创建json数据相对应的类. 也有其他方 ...
- 使用freerdp远程连接Windows桌面
之前使用的是rdesktop,但是由于其不支持NLA认证,便不能登录公司的电脑.为此,现在使用freerdp——这是package的名字,实际的可执行程序是xfreerdp.使用如下的命令行即可实现远 ...
- SourceInsight - 常用设置和快捷键大全
1. 让{ 和 } 不缩进 Options -> Document Options -> Auto Indenting -> Auto Indent Type 选 Simple 2. ...
- 小米2s刷机
每次系统内存不足,卡的不行就恨不得马上换新手机,发现手机也没有什么大的毛病,也没有其他苛刻的要求. 换个新系统继续使用吧,除了屏幕小了一点,将就了吧.物尽其责,坚决抵制过度消费. 小米手机2s 16G ...
- Win7/Win8右键菜单管理工具(Easy Context Menu) v1.5 绿色版
软件名称: Win7/Win8右键菜单管理工具(Easy Context Menu)软件语言: 简体中文授权方式: 免费软件运行环境: Win8 / Win7 / Vista / WinXP软件大小: ...
- 移动前端不得不了解的HTML5 head 头标签(首篇)
HTML的头部内容特别多,有针对SEO的头部信息,也有针对移动设备的头部信息.而且各个浏览器内核以及各个国内浏览器厂商都有些自己的标签元素,有很多差异性.移动端的工作已经越来越成为前端工作的重要内容, ...
- [PHP] 安装和配置
Apachehttpd-2.2.19-win64mysql5.6Phphttp://www.php.net/downloads.php 5.4Phpeclipsehttp://www.phpeclip ...
- The Accomodation of Students(判断二分图以及求二分图最大匹配)
The Accomodation of Students Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d &a ...
- JS获取当前使用的浏览器名字以及版本号
JS获取当前使用的浏览器名字以及版本号 工作中需要通过JS去获取当前使用的浏览器的名字以及版本号,网上大堆资料都有一个关键词是 navigator.appName,但是这个方法获取的浏览器的名字只有两 ...
- 【读书笔记】Linux源码注释
第二章 大概的内部组成 IO端口寻址: 统一寻址: 就是把地址归入存储器寻址范围. 独立寻址: 跟存储器分开,专门的寻址空间 没怎么理解, PC机一般都是采用独立寻址, 见下图 在linux里,可以在 ...