I am a Swift first timer and very much a novice coder. I am trying to adapt the ‘Choose Your Own Story’ app which is here: Choose Your Own Story | Apple Developer Documentation
I want to be able to navigate between the ‘Subject’ page and the ‘Comments’ pages as it already does but when I select an item on the ‘Comments Page’, instead of it just navigating to page 3 as it currently does, I want it to actually copy the text to the clipboard (“Subject 2 Comment A”, for example) so that I can paste that text into a separate document.
Can someone help me out please?
I am not sure how much of this code I need to include, so I have added the lot. Sorry if it is too much!
Many thanks.
// MyStory
import SwiftUI
let story = Story(pages: [
StoryPage( // 0
"""
Subjects...
""",
choices: [
Choice(text: "Subject 1...", destination: 1),
Choice(text: "Subject 2...", destination: 2),
]
),
StoryPage( // 1
"""
Comments 1...
""",
choices:
[
Choice(text: "Return to subject list...", destination: 0),
Choice(text: "Subject 1 Comment A. ", destination: 3),
Choice(text: "Subject 1 Comment B. ", destination: 3),
]
),
StoryPage( // 2
"""
Comments 2...
""",
choices: [
Choice(text: "Return to subject list...", destination: 0),
Choice(text: "Subject 2 Comment A. ", destination: 3),
Choice(text: "Subject 2 Comment B. ", destination: 3),
]
),
StoryPage( // 3
"""
Comment copied to clipboard....
""",
choices: []
),
])
// StoryApp
import SwiftUI
@main
struct StoryApp: App {
var body: some Scene {
WindowGroup {
StoryView()
}
}
}
// StoryModels
struct Story {
let pages: [StoryPage]
subscript(_ pageIndex: Int) -> StoryPage {
if pageIndex == 3 // Added as a debugging test
{let _ = print("Comment copied!")}
return pages[pageIndex]
}
}
struct StoryPage {
let text: String
let choices: [Choice]
init(_ text: String, choices: [Choice]) {
self.text = text
self.choices = choices
}
}
struct Choice {
let text: String
let destination: Int
}
// StoryPageView
import SwiftUI
struct StoryPageView: View {
let story: Story
let pageIndex: Int
var body: some View {
VStack{
ScrollView {
Text(story[pageIndex].text)
ForEach(story[pageIndex].choices, id: \Choice.text) { choice in
NavigationLink(destination: StoryPageView(story: story, pageIndex: choice.destination)) {
Text(choice.text)
.background(Color.gray.opacity(0.25))
}
}
}
.navigationTitle("Page \(pageIndex)")
}
}
}
struct NonlinearStory_Previews: PreviewProvider {
static var previews: some View {
StoryPageView(story: story, pageIndex: 0)
}
}
// StoryView
import SwiftUI
struct StoryView: View {
var body: some View {
NavigationStack {
StoryPageView(story: story, pageIndex: 0)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
StoryView()
}
}