Make writing a habit together! This is the fourth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

In SwiftUI, the function of Text is the same as UILabel in UIKit library, which is used to display static Text. Use as follows:

Text("Hello, world!" )Copy the code

Effect:In the preview window of your content view you will see the prompt “Automatic Preview Updating Paused” and the Resume button, which will allow Swift to start building your code and display it in real time. Of course, you can also use its shortcut keys:option + command + pTo activate it at any time.

By default, Text contains as much of its content as possible, that is, it has many lines. If you don’t want to do this and want to limit the number of lines it displays, you can use lineLimit, as follows:

Text("Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Hello, world!" ) .lineLimit(3)Copy the code

Note that the lineLimit is placed below and to the right of the Text. This style is not necessary. You can also place it after the Text, but this style makes the code more concise and readable.

If you assign a long string to Text and limit the number of lines it can display. SwiftUI defaults to clipping the string and displaying it at the end… .

If you do not want to use this truncation display, you can modify truncationMode to get the desired style. For example, to display the ellipsis from the middle of the text:

Text("Hello, world! Hello, world! Hello, world! Hello, world! Hello,") .lineLimit(1) .truncationMode(.middle)Copy the code

TruncationMode enumeration value

  • Head: if Text does not complete the string, an ellipsis is displayed at the beginning of the string, for example – “… wxyz”
  • Tail: If Text cannot display the entire string, ellipsis is displayed at the end, for example – “abcd…”
  • Middle: If Text cannot complete the string, an ellipsis is displayed in the middle, for example – “ab… yz”

The default value is tail.

Note that no matter how you truncate the text, you will see that the text view is neatly centered in the main view, which is the default behavior of SwiftUI.

It positions views relative to the center of the screen unless it is told to place them elsewhere.