Search code examples
iosstringswiftnsmutableattributedstring

How to align a logo in a String


The currently code allow me to attach a logo. Like this:

But how can I align only the "Logo" sign on the right ? enter image description here

That is what I want: enter image description here

let paragraph = NSMutableAttributedString()

                let font = UIFont(name: "Helvetica Neue", size: 15.0) ?? UIFont.systemFontOfSize(18.0)
                let align = NSTextAlignment.Center

                let textFont = [
                    NSFontAttributeName : font]


                let attrString1 = NSAttributedString(string: "\n Logo", attributes:textFont)
                let attrString2 = NSAttributedString(attributedString: textview.attributedText)


                paragraph.appendAttributedString(attrString2)
                paragraph.appendAttributedString(attrString1)

                let paraStyle = NSMutableParagraphStyle()

                paraStyle.alignment = .Center
                paraStyle.firstLineHeadIndent = 15.0
                paraStyle.paragraphSpacingBefore = 3.0


                paragraph.addAttribute(NSParagraphStyleAttributeName, value: paraStyle, range: NSRange(location: 0,length: paragraph.length))

                shareTextView.attributedText = paragraph

Solution

  • If you want different alignment for different portions, specify different ranges for the two paragraph styles. Thus, you can do something like:

    let centerStyle = NSMutableParagraphStyle()
    centerStyle.alignment = .Center
    
    let rightStyle = NSMutableParagraphStyle()
    rightStyle.alignment = .Right
    
    let font = UIFont(name: "Helvetica Neue", size: 24.0) ?? UIFont.systemFontOfSize(24.0)
    let fontAttributes = [NSFontAttributeName : font]
    
    let attributedText = NSMutableAttributedString(string: "Foo\nBar", attributes: fontAttributes)
    
    attributedText.addAttribute(NSParagraphStyleAttributeName, value: centerStyle, range: NSRange(location: 0, length: 4))
    attributedText.addAttribute(NSParagraphStyleAttributeName, value: rightStyle, range: NSRange(location: 4, length: 3))
    
    textView.attributedText = attributedText
    

    Or, easier, you can append attributed strings with different attributes:

    let font = UIFont(name: "Helvetica Neue", size: 24.0) ?? UIFont.systemFontOfSize(24.0)
    let centerAttributes = [NSFontAttributeName : font, NSParagraphStyleAttributeName : centerStyle]
    let attributedText = NSMutableAttributedString(string: "Foo\n", attributes: centerAttributes)
    
    let rightAttributes = [NSFontAttributeName : font, NSParagraphStyleAttributeName : rightStyle]
    attributedText.appendAttributedString(NSMutableAttributedString(string: "Bar", attributes: rightAttributes))
    
    textView.attributedText = attributedText
    

    That yields:

    enter image description here