Line Break with Text() in SwiftUI

11,484

lineLimit API is used whenever you want a specific number of lines in the Text, you just call this API with number of lines that you want. If you are not sure how many lines will the take, just give nil in the parameter.

import SwiftUI
struct ContentView : View {
    @State var demoText = "Start Typing"
    var body: some View {
        VStack {
            TextField($demoText)
            Text(demoText)
                .lineLimit(nil)
        }
    }
}
Share:
11,484
Adrian Baumgart
Author by

Adrian Baumgart

Updated on June 08, 2022

Comments

  • Adrian Baumgart
    Adrian Baumgart about 2 years

    How do I make a line break with Text() if the text is too long to display in one line? (Something like lineBreakMode in UIKit)

    If I type in a long string it just adds „...“ on the right side of the text.

    Thanks!

    Edit: I tried to combine it with a scroll view to be able to scroll if the text is too long, but if I add a scroll view it ignors .lineLimit()

    Code:

    ˋˋˋ

    struct Homework: View {
    
    var selectedWeek: String
    var week: String = "10.-20."
    var content: String = "" //Long string inside here
    
    var body: some View {
        NavigationView {
            ScrollView(isScrollEnabled: true, alwaysBounceHorizontal: false, alwaysBounceVertical: true, showsHorizontalIndicator: false, showsVerticalIndicator: true, content: {
                Text(content)
                   .lineLimit(nil)
            })
                .navigationBarTitle(Text(week))
        }
    }
    }
    

    ˋˋˋ

  • Adrian Baumgart
    Adrian Baumgart almost 5 years
    Without any extra code it works, but if I add a scroll view, it doesn‘t work... Sorry.
  • Md Shafiul Islam
    Md Shafiul Islam almost 5 years
    In that case Text should be scrollable. There will be no ... shown at the end of the text.
  • Adrian Baumgart
    Adrian Baumgart almost 5 years
    Shaafi Shovon, I am not able to scroll with this code. It shows "..." at the end of the text
  • Md Shafiul Islam
    Md Shafiul Islam almost 5 years
    If i embed the code that I have posted here in a ScrollView then the text label becomes horizontally scrollable. So I am not sure about your code, what could have gone wrong.
  • Adrian Baumgart
    Adrian Baumgart almost 5 years
    Yes this is what i mean with "it ignors .lineLimit()". The text displays in one scrollable line. I fixed the problem temporarily with a List...