centering text in a UILabel with an NSAttributedString

后端 未结 3 656
清歌不尽
清歌不尽 2021-02-02 06:57

Going through some basic improvements to a application I am working on. Still new to the iOS swift development scene. I figured that the lines of text in my code would automatic

3条回答
  •  天涯浪人
    2021-02-02 07:10

    You need to create a paragraph style specifying center alignment, and set that paragraph style as an attribute on your text. Example playground:

    import UIKit
    import PlaygroundSupport
    
    let style = NSMutableParagraphStyle()
    style.alignment = NSTextAlignment.center
    
    let richText = NSMutableAttributedString(string: "Going through some basic improvements to a application I am working on. Still new to the iOS swift development scene. I figured that the lines of text in my code would automatically be centered because I set the label to center.",
                                             attributes: [ NSParagraphStyleAttributeName: style ])
    // In Swift 4, use `.paragraphStyle` instead of `NSParagraphStyleAttributeName`.
    
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 400))
    label.backgroundColor = UIColor.white
    label.attributedText = richText
    label.numberOfLines = 0
    PlaygroundPage.current.liveView = label
    

    Result:

    Since you're parsing an HTML document to create your attributed string, you'll need to add the attribute after creation, like this:

    let style = NSMutableParagraphStyle()
    style.alignment = NSTextAlignment.center
    
    let richText = try NSMutableAttributedString(
        data: assetDetails!.cardDescription.data(using: String.Encoding.utf8)!,
        options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
        documentAttributes: nil)
    richText.addAttributes([ NSParagraphStyleAttributeName: style ],
                           range: NSMakeRange(0, richText.length))
    // In Swift 4, use `.paragraphStyle` instead of `NSParagraphStyleAttributeName`.
    assetDescription.attributedText = richText
    

    Update for Swift 4

    In Swift 4, attribute names are now of type NSAttributeStringKey and the standard attribute names are static members of that type. So you can add the attribute like this:

    richText.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, richText.length))
    

提交回复
热议问题