gpt4 book ai didi

ios - 使用swift根据文本中的字符创建NSMutableAttributedString

转载 作者:搜寻专家 更新时间:2023-11-01 05:42:16 24 4
gpt4 key购买 nike

我有一组按钮标签:

whenButtonArray = ["THURSDAY\nJUNE 5", "FRIDAY\nJUNE 6", "SATURDAY\nJUNE 7", "SUNDAY\nJUNE 8"]

我想做的是使用 NSMutableAttributedString 使“\n”之前的文本比它之后的文本字体更大。

我这样初始化我的字符串:

myMutableString = NSMutableAttributedString(string: whenWhereButtonArray[i], attributes: [NSFontAttributeName:UIFont(name: "Tungsten-Book", size: 22.0)!])

但是我怎样才能使字符串的第二部分(\n 之后)的字体变小呢?我知道我可以做这样的事情:

myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Tungsten-Book", size: 12.0)!, range: NSRange(location:3,length:4))

但我需要根据每个按钮的文本动态调整范围。谢谢!

最佳答案

只要您的字符串中没有 Unicode 字符表示/表情符号,以下内容就应该有效。否则最好使用 NSString,如 rintaro 的回答...

为了根据子属性的需要动态更新剩余字符串的位置和长度,您必须首先获取“\n”的位置(我使用了 this 答案中的公式。) :

let range = whenWhereButtonArray[i].rangeOfString("\n")
let newlineIndex : Int = distance(whenWhereButtonArray[i].startIndex, range.startIndex)

然后知道“\n”的开始索引,您可以计算 (1) 第二个字符串的索引,然后 (2) 第二个字符串的长度。例如:

let secondStringIndex : Int = newlineIndex + countElements("\n")
let lengthOfSecondString : Int = countElements(whenWhereButtonArray[i]) - secondStringIndex

然后您可以像这样将该信息输入到子属性公式中:

myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Tungsten-Book", size: 12.0)!, range: NSRange(location:secondStringIndex,length:lengthOfSecondString))

关于ios - 使用swift根据文本中的字符创建NSMutableAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com