如何将文本修饰符应用于包含文本的自定义视图中的 SwiftUI

huangapple go评论78阅读模式
英文:

SwiftUI how to apply text modifier to custom view with Text in it

问题

我创建了一个自定义文本组件,它包装了文本内容。

struct ScrollText: View {
    let text: String
    var body: some View {
        Text("\(text) the logic is like that")
    }
}

然后,我希望这个视图可以使用Text的修饰符,比如.font.fontWeight.tracking

ScrollText(text: "abcdefg")
     .font(.body)
     .tracking(-0.3)

但我发现在iOS 15中只有.font可以正常工作。我该怎么做才能使它像普通的Text组件一样工作?

英文:

I create a custom text component, which wraps the Text in it.

struct ScrollText:View{
    let text: String
    var body: some View {
        Text("\(text) the logic is like that")
    }
}

Then I want this view can use the modifier of Text such as .font, .fontWeight, .tracking

ScrollText(text:"abcdefg")
     .font(.body)
     .tracking(-0.3)

But I found that in iOS 15 only .font can work.
What can I do to make it work as the normal Text component?

答案1

得分: 0

在iOS 15中,为什么文本修饰符不能用在我的自定义视图中是因为这些修饰符只适用于类型 "Text",而我们的视图返回的是 "some View"。

所以可以通过以下方式实现:

extension Text {
    func addaPlus(activate: Bool) -> some View {
        return ScrollText(text: self, activate: activate)
    }
}

在这个函数中,self 意味着文本,而不是将字符串传递给视图,我们将文本放在最后的位置,将文本转换为某个视图。

顺便说一下,我不知道如何通过这样做来读取和修改文本中的字符串。

Text(longText)
     .tracking(-0.3)
     .addaPlus(activate: activate)

但是,如果你可以返回 "Text" 而不是 "some View",你仍然可以在此之后使用文本专用的修饰符。

英文:

Why text modifiers can not be used in my custom view is that in iOS 15, these modifiers only works with type "Text", but our view return "some View" instead.

So it can be done by using

extension Text{
    func addaPlus(activate:Bool)->some View{
        return ScrollText(text: self, activate: activate)
    }
}

In this function, self means Text, and instead of passing the string to the view we pass the Text and place it in the last position, which transforms the Text to some View.

By the way, I don't know how to read and modify the string inside the text by doing this.

 Text(longText)
         .tracking(-0.3)
         .addaPlus(activate: activate)

But if you can return Text instead of some View, you can still use Text-only modifiers below this one.

huangapple
  • 本文由 发表于 2023年6月19日 22:29:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定