如何在 swift ui 中适应形状以适应文本视图的长度和宽度

pet*_*erk 2 swift swiftui

这就是我想要在我的代码中发生的事情,我希望矩形可以缩放到任何字体大小。

ZStack{
                        RoundedRectangle(cornerRadius: 8).foregroundColor(.red).scaledToFit()//.frame(width: 200, height: 25)
                        HStack{
                            Image(systemName: "tag.fill").foregroundColor(.white)
                            Text("Tickets Not Available").font(.headline).foregroundColor(.white).fixedSize(horizontal: true, vertical: false)
                        }
                    }.scaledToFit()
Run Code Online (Sandbox Code Playgroud)

如您所见,我的视图放置在 zstack 中,以便圆角矩形可以作为文本视图的背景。我已经尝试了很多不同的事情,比如把 .scaledtofit 放在哪里,但它每次都给我带来了古怪的结果。

wor*_*dog 5

这是你所追求的吗(注意 Image.resizable):

import SwiftUI

struct ContentView: View {

var body: some View {
    ZStack{
        RoundedRectangle(cornerRadius: 8).foregroundColor(.blue)
        HStack{
            Image(systemName: "tag.fill").resizable().padding(4).foregroundColor(.white).scaledToFit()
            Text("Get Tickets").font(.headline).foregroundColor(.white)
        }
    }.fixedSize()
}
Run Code Online (Sandbox Code Playgroud)