ios - 如何对齐字符串中的 Logo

标签 ios string swift nsmutableattributedstring

当前代码允许我附加一个标志。像这样:

但是我怎样才能只对齐右边的“Logo”标志呢? enter image description here

这就是我想要的: 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

最佳答案

如果您希望不同部分采用不同的对齐方式,请为两种段落样式指定不同的范围。因此,您可以执行以下操作:

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

或者,更简单的是,您可以附加具有不同属性的属性字符串:

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

产生:

enter image description here

关于ios - 如何对齐字符串中的 Logo ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31854929/

相关文章:

swift 如何使渐变层从不同的位置开始

swift - 我如何允许拥有自己的松弛帐户/公司的用户在我的应用程序中登录到他们的松弛帐户

ios - 观察者调用的函数没有动画

ios - 如何在运行时为 UIBarButtonItem 设置目标和操作

java - 无法获取子字符串的子字符串

c - 在 C 中比较两个字符串的最快方法是什么?

string - Lua 模式用于替换任何单词、字符、数字或符号,后跟特定字符串

ios - 关联的枚举类型实现 CaseItratable

ios - 带条件的 Swift 过滤器

ios - Swift 无法从 JSON api 读取普通话?