Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI conditional Text modifier .textSelection

maybe a absolute beginner question:
In the following code is foregroundColor working but .textSelection doesn’t. What is the reason?

Text("This is a Test")
  .foregroundColor(isSelectable ? .green : .red)
  .textSelection(isSelectable ? .enabled : .disabled)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

We cannot put it ternary operator, because .enabled and .disabled are of different concrete types (confirming to one protocol), so possible variant is

let text = "This is a Test"
Group {
    if isSelectable {
        Text(text)
          .textSelection(.enabled)
    } else {
        Text(text)
          .textSelection(.disabled)
    }
}
.foregroundColor(isSelectable ? .green : .red)

Note: actually Apple does not consider this feature as togglable, let’s read the doc

/// A selectability value that enables text selection by a person using your app.
///
/// Enabling text selection allows people to perform actions on the text
/// content, such as copying and sharing. Enable text selection in views
/// where those operations are useful, such as copying unique IDs or
/// error messages. This allows people to paste the data into
/// emails or documents.

It’s hardly imaginable that "useful informations electability" can be turned of for some reason. Just in case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading