微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 SwiftUI 中的形状上添加多个文本叠加

如何解决在 SwiftUI 中的形状上添加多个文本叠加

我正在开发一个项目,在该项目中我在 SwiftUI 中使用了不同的形状,例如这个 RoundedRectangle。 我想通过叠加在其上添加文本,但它不允许我添加多于一行。我试图搜索一些叠加教程,但总是找到只显示 -one life of text - 示例的教程。

所以我想知道是否有办法在这样的形状上添加多行文本叠加,或者是否有更好的方法来处理它。

感谢您的反馈。

这是当前代码

import SwiftUI


struct ContentView: View {
    var body: some View {
        
        HStack {
        RoundedRectangle(cornerRadius: 20)
            .frame(width: 320,height: 200)
            .foregroundColor(Color.blue)
            .overlay(
                Text("Hello there")
           )
            
      }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

这是我理想中想要的,但这样就行不通了:

import SwiftUI


struct ContentView: View {
    var body: some View {
        
        HStack {
        RoundedRectangle(cornerRadius: 20)
            .frame(width: 320,height: 200)
            .foregroundColor(Color.blue)
            .overlay(
                Text("Hello there")
                Text("Hello there")
                Text("Hello there")
                Text("Hello there")
                Text("Hello there")
                Text("Hello there")
                
           )
            
      }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

解决方法

将您的文本与 GroupVStackHStack 等中的任何一个包装在一个容器中。

struct ContentView: View {
    var body: some View {
           HStack {
           RoundedRectangle(cornerRadius: 20)
               .frame(width: 320,height: 200)
               .foregroundColor(Color.blue)
               .overlay(
                Group{ //<-- Here
                   Text("Hello there")
                   Text("Hello there")
                   Text("Hello there")
                   Text("Hello there")
                   Text("Hello there")
                   Text("Hello there")
                }
              )
         }
       }
}

或者您可以使用 @ViewBuilder

struct ContentView: View {
    var body: some View {
           HStack {
           RoundedRectangle(cornerRadius: 20)
               .frame(width: 320,height: 200)
               .foregroundColor(Color.blue)
               .overlay(
                overlayView
              )
         }
       }
    
    // Make your view here
    @ViewBuilder
    private var overlayView: some View {
        Text("Hello there")
        Text("Hello there")
        Text("Hello there")
        Text("Hello there")
        Text("Hello there")
        Text("Hello there")
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。