26
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでUILabelにAttributedStringを設定するメモ

Last updated at Posted at 2015-04-21

NSMutableAttributedStringを使ったやり方のメモ

sample.swift
let attrText = NSMutableAttributedString(string: "装飾される文字列")

// 文字色
attrText.addAttributes([NSForegroundColorAttributeName: UIColor.blueColor()], range: NSMakeRange(1, 4))

// 背景色
attrText.addAttributes([NSBackgroundColorAttributeName: GSSettings.unreadNotificationColor()], range: NSMakeRange(1, 4))

// フォント(Bold、サイズはUILabelの標準サイズ)
attrText.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.labelFontSize())], range: NSMakeRange(0, 1))

self.label.attributedText = attrText

ちなみに、NSLinkAttributeNameを使ってリンクっぽい装飾はできるが、タップイベントは発生しない模様。。

link.swift
attrText.addAttributes([NSLinkAttributeName: NSURL(string: "http://google.co.jp")!], range: NSMakeRange(0, 4))
26
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?