Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Prevent word break for long words

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

like image 431
BlackMouse Avatar asked Sep 19 '25 00:09

BlackMouse


1 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)
            }
        )
    }
    
}
like image 144
ios coder Avatar answered Sep 22 '25 15:09

ios coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!