Search code examples
textviewscaleswiftuiscaling

SwiftUI - Text minimumScaleFactor not scaling only when needed


I have a Text that I want to modify with a .minimumScaleFactor(0.1) when the length of its string extends outside the view. However, the scaling applies every time, even when the original font size would be perfectly fine.

My view is structured thusly:

        VStack(alignment: .center, spacing: 0) {
            HStack {
                Image("medal \(place)").resizable()
                    .foregroundColor(color)
                    .frame(width: 40, height: 40)
                Spacer()
                Text(username)
                    .font(.bold(16))
                    .lineLimit(1)
                    .minimumScaleFactor(0.1)
                    .frame(alignment: .trailing)
                    .foregroundColor(Color("mediumTextColor"))
            }
            Spacer()
            Text(score)
                .font(.extraBold(60))
                .foregroundColor(color)
                .lineLimit(1)
                .minimumScaleFactor(0.7)

            Spacer()
        }
        .frame(height: 96)
        .padding(10)
        .cornerRadius(16)
        .overlay(RoundedRectangle(cornerRadius: 16)
        .stroke(color, lineWidth: 2))

Solution

  • Adding a GeometryReader around the VStack that my two Text views were in solved this. As requested by @gohnjanotis:

    GeometryReader { proxy in
        VStack(alignment: .center, spacing: 0) {
            HStack {
                Image("medal \(self.place)").resizable()
                    .foregroundColor(self.color)
                    .frame(width: 40, height: 40)
    
                Spacer()
                Text(self.username)
                    .minimumScaleFactor(0.1)
                    .font(.bold(16))
                    .lineLimit(1)
                    .frame(alignment: .trailing)
                    .foregroundColor(Color("mediumTextColor"))
                    .layoutPriority(1)
    
            }
            .padding(.top, 10)
            .padding(.horizontal, 10)
            Spacer()
            Text(self.score)
                .font(.extraBold(60))
                .foregroundColor(self.color)
                .lineLimit(1)
                .minimumScaleFactor(0.1)
                .layoutPriority(1)
                .padding(.horizontal, 10)
                .padding(.bottom, 10)
                .offset(y: -10)
        }
        .frame(width: proxy.size.width, height: proxy.size.height, alignment: .top)
    }
    .frame(maxHeight: 130)