在给定字符串The * quick * brown * fox * jumps * over * the * lazy * dog的情况下,我按如下方式应用字体修饰符,以使all occurrences of asterisk的样式与文本的其余部分不同.

func customDesc(_ text: String) -> NSMutableAttributedString {
        let asteriskTextRange = (text as NSString).range(of: "*")
        let attributedString = NSMutableAttributedString(string: text, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15, weight: .semibold)])
        attributedString.setAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20, weight: .heavy)], range: asteriskTextRange)
        return attributedString
    }

看起来range(of:)只会 Select 第一个匹配项,那么如何更新所有匹配项并在Text视图中显示结果文本呢?我找不到任何接受NSMutableAttributedString的初始值设定项.如有任何帮助,我们不胜感激.

推荐答案

Texts用Swift AttributedStrings代替客观C的NSAttributedStrings.您只需使用其初始化器之一即可转换为AttributedString.

Text(AttributedString(customDesc(...)))

然而,我建议customDesc直接返回AttributedString,因为它更快速.您可以使用ranges(of:)查找特定子字符串的所有范围.

func customDesc(_ text: String) -> AttributedString {
    var attributedString = AttributedString(text)
    attributedString.font = Font.system(size: 15, weight: .semibold)

    for range in text.ranges(of: "*") {
        // this converts Range<String.Index> to Range<AttributedString.Index>
        if let lowerBound = AttributedString.Index(range.lowerBound, within: attributedString),
           let upperBound = AttributedString.Index(range.upperBound, within: attributedString) {
            let attrRange = lowerBound..<upperBound
            attributedString[attrRange].font = Font.system(size: 20, weight: .heavy)
        }
    }
    return attributedString
}
Text(customDesc(...))

Swift相关问答推荐

为什么我的引用类型对象在初始化后有3个强引用?

绑定到可选值的非可选属性?'

在Swift中,是否只有iOS版本超过15才能导入Swift包?

编写Swift字符串的属性包装时遇到问题

SwiftUI:为什么@State在子视图中持续存在?

出错-无法将季节类型的值转换为预期的参数类型';[水果]';

如何在SwiftUI中做出适当的曲线?

KMM-Swift铸造密封类

SwiftUI 组合问题:通过 AppEventsManager 在 ViewModel 之间共享数据

使用异步收集发布者值

在 RealmSwift 中表示范围值?

关于变量的视图的 SwiftUI 生命周期

LeetCode 249. 分组移位字符串

为什么 Apple Scrumdinger Sample App 使用两个事实来源?

故事板未在助手中显示视图控制器

将数据附加到 Firebase 实时数据库后,NavigationLink 将我重定向到上一个视图

SwiftUI 4 列表初始化程序在 iOS 中不可用

调用从 SwiftUI 视图传递到 PageViewController.Coordinator 的函数

组合 flatMap 不会返回预期的上下文结果类型

iOS 判断应用程序是否可以访问麦克风