Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 516
A. Lucas Avatar asked Oct 25 '19 18:10

A. Lucas


3 Answers

Important for that minimumScaleFactor() only does its job when it is needed, is the combination of .minimumScaleFactor AND .lineLimit(1); otherwise it will not work. layoutPriority(1) is not the key here.

Example - this works; Scale is only applied when needed:

Text("Something").minimumScaleFactor(0.5).lineLimit(1)
like image 94
NeoLeon Avatar answered Sep 17 '22 16:09

NeoLeon


A continuation of answer above.

What is important is the order in which the modifiers are applied:

Text("This is a really long sentence.") 
   .minimumScaleFactor(0.5)                
   .font(.custom("OpenSans", size: 15))
   .lineLimit(1)
   .layoutPriority(1)

There isn't a need for the GeometryReader unless you need it for something else

like image 7
Alexander Avatar answered Nov 08 '22 23:11

Alexander


Adding .lineLimit(1) to the Text will work well.

Xcode: 11.3.1

like image 5
mishimay Avatar answered Nov 08 '22 22:11

mishimay