skip to Main Content

I’m trying to figure out how can I show only the first letter of the text?

struct MyText: View {
    var body: some View {
        
        Text("Hello")
            .lineLimit(1)
        
    }
}

This is how it should turn out

H

I tried using Line limit but as far as I know it only displays the text in one line

2

Answers


  1. This can be done using the first property of the string:

    "Hello".first
    // -> "H"
    
    Login or Signup to reply.
  2. Every String has the first property which returns the first Character of the string. Now because Characters cannot be downcasted to String, here’s what you need to do:

    let text = "Hello"
    
    if let firstCharacter = text.first {
        Text(String(firstCharacter))
    } else {
        // do something else
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search