iOS 教程:属性字符串

原文链接:https://www.ioscreator.com/tutorials/attributed-strings-ios-tutorial-ios10
作者:Arthur Knopper
原文日期:2017/04/04
译者:Crystal Sun

译者注:本文是之前一篇文章的更新版本,旧文链接,旧文使用的 Swift 版本不是 3.0,本文更新了代码,升级到了 Swift 3.0。

属性字符串(Attributed Strings)可以为文本赋予各种各样的属性,还能一次给(部分)文本赋值多个属性。在本节教程中,将学会给 label 文本里的每个单词各设置不一样的样式。本节教程使用的是 Xcode 8 和 iOS 10。

打开 Xcode,创建一个 Single View Application。

Product Name 使用 IOS10AttributedStringsTutorial,填写自己的 Organization Name 和 Organization Identifier,Language 一栏选择 Swift,Devices 一栏选择 iPhone。

打开 Storyboard,从 Object-Library(控件库)中拖拽一个 Label 控件到主界面,点击 Storyboard 右下角 Auto Layout 的 Align 按钮,添加下图所示约束,点击 “Add 1 Constraint”。。

点击 Auto Layout 的 Pin 按钮,添加如下图所示约束,点击 “Add 1 Constraint”。

点击 Assistant Editor,确保 ViewController.swift 文件可见。按住 Control 键,将 Label 控件拖拽到 ViewController 类下面,创建下列 Outlet 连接。

打开 ViewController.swift 文件,如下所示对 viewDidLoad 方法进行修改。

override func viewDidLoad() {
    super.viewDidLoad()
        
    // 1
    let string = "Testing Attributed Strings"
    let attributedString = NSMutableAttributedString(string: string)
        
    // 2
    let firstAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.blue, NSBackgroundColorAttributeName: UIColor.yellow, NSUnderlineStyleAttributeName: 1]
    let secondAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.red, NSBackgroundColorAttributeName: UIColor.blue, NSStrikethroughStyleAttributeName: 1]
    let thirdAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.green, NSBackgroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFont(ofSize: 40)]
        
    // 3
    attributedString.addAttributes(firstAttributes, range: NSRange(location: 0, length: 8))
    attributedString.addAttributes(secondAttributes, range: NSRange(location: 8, length: 11))
    attributedString.addAttributes(thirdAttributes, range: NSRange(location: 19, length: 7))
        
    // 4
    attributedLabel.attributedText = attributedString
}
  1. 创建一个普通的字符串,将会转换成多种属性字符串。
  2. 创建见 3 个字典,存储属性的键和值。
  3. 将属性添加到 attributedString 对象中。
  4. 最后,将属性字符串赋值给 Label。

运行程序,属性字符串的实现效果如下。

可以从 github 上下载 IOS10AttributedStringsTutorial 教程的源代码。

本文由 SwiftGG 翻译组翻译,已经获得作者翻译授权。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作者:Arthur Knopper,原文链接,原文日期:2017-04-04译者:Crystal Sun;校对:w...
    梁杰_numbbbbb阅读 1,327评论 1 2
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,192评论 4 61
  • 每个故事的背后还藏有另一个故事 有人喜欢听,有人喜欢写!我知道你也是有故事的人,只是忘了从何说起。
    陈靡靡阅读 305评论 1 2
  • 之前在简书上看过一个大神写过,但是讲得不是很明白。最近没事儿我就把他封装了一下。先看效果: 分析: 底层放置一个U...
    离开是场无止境旅行阅读 2,213评论 5 52
  • 你說,外面下着雨,我們寫着字,多搞笑。我走近窗臺,望着路燈下的水窪,那濺起的水花,似乎要打進在十四樓的心房。 『分...
    Boyd阅读 311评论 0 3