【问题标题】:SwiftUI highlight word in search resultSwiftUI 在搜索结果中突出显示单词
【发布时间】:2023-03-17 08:37:01
【问题描述】:

我有一个搜索视图,用户可以在其中按单词或短语搜索并过滤结果。

        List {
            ForEach(textsData) {text in
                if text.sometext.localizedCaseInsensitiveContains(self.searchText) || self.searchText == "" {
                    NavigationLink(destination: TextView(text: text)) {
                        Text(text.sometext)
                    }
                }
                
            }
        }

我想用红色突出显示搜索到的文本。有什么办法可以吗?

UPD: 假设代码如下:

struct ContentView: View {
    
    var texts = ["This is an example of large text block", "This block is rather small"]
    
    var textsSearch = "large"
    
    var body: some View {
        List {
            ForEach(self.texts, id: \.self) {text in
                Text(text).padding().background(self.textsSearch == text ? Color.red : .clear)
            }
        }
    }
}

我只想在输出中突出显示“大”这个词:

这是文本块的示例

这个块比较小

UPD2:这个答案对我很有效:SwiftUI: is there exist modifier to highlight substring of Text() view?

【问题讨论】:

    标签: swiftui uisearchbar


    【解决方案1】:

    这应该可行。您通常可以将条件直接添加到修饰符中:

    struct ContentView: View {
        
        var texts = ["a", "b"]
        
        var textsSearch = "a"
        
        var body: some View {
            List {
                ForEach(self.texts, id: \.self) {text in
                    Text(text).padding().background(self.textsSearch == text ? Color.red : .clear)
                }
            }
        }
    }
    
    

    【讨论】:

    • 感谢您的评论!不幸的是,这仅在文本值完全等于搜索值时才有效。在我的情况下,文本值可能具有“这是大文本块的示例”并且 searchTest 可能是“大”。所以我想在文本输出中突出显示“大”这个词
    • 在这种情况下我应该怎么做才能突出显示“大”这个词? struct ContentView: View { var texts = ["This is an example of large text block", "This block is rather small"] var textsSearch = "large" var body: some View { List { ForEach(self.texts, id: \.self) {text in Text(text).padding().background(self.textsSearch == text ? Color.red : .clear) } } } }
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2012-04-01
    相关资源
    最近更新 更多