iOSチュートリアル:属性文字列

2407 ワード

作者:Arthur Knopper,原文リンク,原文日付:2017-04-04
Crystal Sun;校正:way;下書き:shanks
本文は前の1篇の文章の更新バージョンで、古い文のリンク、古い文が使うSwiftバージョンは3.0ではありませんて、本文はコードを更新して、Swift 3.0にアップグレードしました.
属性文字列(Attributed Strings)は、テキストに様々な属性を付与したり、一度に複数の属性を付与したりすることができます.このチュートリアルでは、labelテキストの単語ごとに異なるスタイルを設定することを学びます.このチュートリアルでは、Xcode 8とiOS 10を使用します.
Xcodeを開き、Single Viewアプリケーションを作成します.
Product Name IOS 10 AttributedStringsTutorialを使用して、自分のOrganization NameとOrganization Identifier、Languageの欄はSwift、Devicesの欄はiPhoneを選択します.
Storyboardを開き、Object-Library(コントロールライブラリ)からLabelコントロールをメインインタフェースにドラッグし、Storyboard右下のAuto LayoutのAlignボタンをクリックし、下図に示す制約を追加し、「Add 1 Constraint」をクリックします.
AutoLayoutの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
}
  • 通常の文字列を作成し、複数の属性文字列に変換します.
  • は、3つの辞書を作成し、属性のキーと値を格納します.
  • は、attributedStringオブジェクトに属性を追加します.
  • 最後に、属性文字列をLabelに割り当てます.

  • プログラムを実行し、属性文字列の実現効果は以下の通りです.
    IOS 10 AttributedStringsTutorialチュートリアルのソースコードはgithubからダウンロードできます.
    本文はSwiftGG翻訳グループから翻訳して、すでに作者の翻訳の授権を得て、最新の文章は訪問して下さいhttp://swift.gg.