Read only yet selectable text in SwiftUI

Hi all,

I am trying to implement a Copy Text option for read only text output just like the iOS calculator output using SwiftUI 2.0 (Swift 5.3)

I want the user to be able to copy the text, and nothing more. Surprisingly simple yet I can't figure out how to do it any help greatly appreciated!

Thanks.
Answered by LogicalLight in 678473022

I think you'll be happy with .textSelection(.enabled) in the next release of SwiftUI.

You may consider implementing it like this:

Code Block
Text(readOnlyTextString)
.contextMenu {
Button(action: {
UIPasteboard.general.string = readOnlyTextString
}) {
Text("Copy")
}
}


Accepted Answer

I think you'll be happy with .textSelection(.enabled) in the next release of SwiftUI.

Extra info when I added this modifier Xcode suggested the following for backwards compatibility for older iOS devices.

Text("To be, or not to be, that is the question:")
if #available(iOS 15.0, *) {
Text("To be, or not to be, that is the question:").textSelection(.enabled)
} else {
// Fallback on earlier versions
}
Read only yet selectable text in SwiftUI
 
 
Q