SwiftUI: Prevent word break for long words

Viewed 566

How do I prevent word breaking for long words, e.g adjust font size to fit width?

Requirements: The outer gray frame must have the same fixed size. The should be 2 lines.

var body: some View {
VStack {
    Spacer()

    Image(systemName: "square")

                .resizable()
                .frame(width: 50, height: 50)
        
        Spacer()
        Text("Acknowledgement for the rest")
            .allowsTightening(true)
            .minimumScaleFactor(0.01)
            .lineLimit(2)
            .multilineTextAlignment(.center)
        
    }
    .padding()
    .frame(width: 140, height: 150, alignment: .center)
    .background(
        ZStack {
            RoundedRectangle(cornerRadius: 10)
                .foregroundColor(Color(hex: "f9f9f9"))
        }
    )

}

enter image description here

2 Answers

use fixedSize modifier:


enter image description here


import SwiftUI

struct ContentView: View {
    
    var body: some View {
        VStack {
            Spacer()
            
            Image(systemName: "square")
                .resizable()
                .frame(width: 50, height: 50)
            
            Spacer()
            Text("Acknowledgement for the rest")
                .fixedSize()    // <<: Here
                .allowsTightening(true)
                .minimumScaleFactor(0.01)
                .lineLimit(nil)
                .multilineTextAlignment(.center)
            
        }
        .padding()
        .frame(height: 150)
        .background(
            ZStack {
                RoundedRectangle(cornerRadius: 10)
                    .foregroundColor(Color.blue)
            }
        )
    }
    
}

as you mention in the comment

The text coming in is dynamic. Is might be very long or very short. I want to adjust the font size to fit.

it will adjust the font size to fit the width.enter image description here

struct ContentView: View {

@State var acknowledgementString = "acknowledgement for the rest"
let mainWidth : CGFloat = 350//140
var body: some View  {
    Text(acknowledgementString)
        .font(.system(size: 100))
        .minimumScaleFactor(0.01)
        .lineLimit(1)
        .frame(width: mainWidth,height: mainWidth,alignment: .center )
        .background(Color.red)
        .onTapGesture {
            acknowledgementString += " extra"
        }
   } 
  }
Related