Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fit a shape in swift ui to accommodate the length and width of a text view

Tags:

swift

swiftui

This is what I want to happen in my code and I want the rectangle to scale to whatever font size.

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()

As you can see my views are placed in a zstack so that the rounded rectangle can be the background of the text view. I've tried so many different things like where to put the .scaledtofit and it just gives me wack results each time.

like image 892
peterk Avatar asked Oct 20 '25 15:10

peterk


1 Answers

is this what you're after (note the 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()
}
like image 193
workingdog support Ukraine Avatar answered Oct 23 '25 07:10

workingdog support Ukraine