Swift Playgrounds

RSS for tag

Learn and explore coding in Swift through interactive learning experiences on the Swift Playgrounds app for iPadOS and macOS.

Swift Playgrounds Documentation

Posts under Swift Playgrounds tag

116 Posts
Sort by:
Post not yet marked as solved
0 Replies
404 Views
Im making an app that uses drag&drop but, it doesn't work. This is made with Swift Playground. If you can find a solution, please let me know. Here is the code. //MARK: Drop Area @ViewBuilder func DropAera()->some View{ VStack(spacing: 12){ ForEach($rows,id:\.self){$row in HStack(spacing: 10){ ForEach($row){$item in Text(item.value) .font(.system(size: item.fontSize)) .padding(.vertical,5) .padding(.horizontal,item.padding) .opacity(item.isShowing ? 1 : 0) .background{ RoundedRectangle(cornerRadius: 6, style: .continuous) .fill(item.isShowing ? .clear : .gray.opacity(0.25)) } .background{ // If Item is Dropped into Correct Plase RoundedRectangle(cornerRadius: 6, style: .continuous) .stroke(.gray) .opacity(item.isShowing ? 1 : 0) } // MARK: Adding Drop Operation // MARK: Adding Drag Drop Operation .onDrop(of: [.url], isTargeted: .constant(false)) { providers in if let first = providers.first{ let _ = first.loadObject(ofClass: URL.self) { value,error in guard let url = value else{return} if item.id == "\(url)"{ droppedCount += 1 let progress = (droppedCount / CGFloat(characters.count)) withAnimation{ item.isShowing = true updateShuffledArray(character: item) self.progress = progress } } else{ //Animating When Wrong text animateView() } } } return false } } } if rows.last != row{ Divider() } } } } @ViewBuilder func DragArea()->some View{ VStack(spacing: 12){ ForEach(shuffledRows,id: \.self){row in HStack(spacing: 10){ ForEach(row){item in Text(item.value) .font(.system(size: item.fontSize)) .padding(.vertical,5) .padding(.horizontal,item.padding) .background{ RoundedRectangle(cornerRadius: 6, style: .continuous) .stroke(.gray) } // MARK: Adding Drag Drop Operation .onDrag{ // Returning ID to find whitch Item is Moving return .init(contentsOf: URL(string: item.id))! } .opacity(item.isShowing ? 0 : 1) .background{ RoundedRectangle(cornerRadius: 6, style: .continuous) .fill(item.isShowing ? .gray.opacity(0.25) : .clear) } } } if shuffledRows.last != row{ Divider() } } } }
Posted
by
Post not yet marked as solved
1 Replies
425 Views
Hello, The appearance of one of my buttons is not updating after being tapped. I have had no trouble doing the exact same thing in my other views, but here it simply doesn't work. The "heart" button will keep its original appearance (in this case an unfilled heart) no matter what, despite my print statements indicating that the value has changed. The other actions performed when tapping the heart work perfectly. I've been at it for hours. Any help would be appreciated. Thanks! import SwiftUI struct SearchView: View { @State private var searchText = "" @StateObject var save = SaveWords() @State var heart: String? @State var disappear = false @State var done = true var body: some View { NavigationView { VStack { if !disappear { SearchBarView(text: $searchText) Spacer() } if searchText != "" { List(.constant(Array(FetchWord.getWordFromStart(start: searchText)).prefix(10).map {Word(word: $0.1)})) { suggestion in NavigationLink(destination: suggestion.IPA.wrappedValue == "error" ? AnyView(EmptyView()) : AnyView(PracticeView(wordSheet: suggestion) .onAppear { disappear = true if done { SaveWords.file = "Favorites" DispatchQueue.main.async { Task { try? await save.load() heart = save.words.contains(suggestion.wrappedValue) ? ".fill" : "" } } } } .onDisappear { disappear = false Task { SaveWords.file = "History" try? await save.load() if save.words.first != suggestion.wrappedValue { save.words.insert(suggestion.wrappedValue, at: 0) try? await save.save() } } } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: { SaveWords.file = "Favorites" done = false if heart == "" { heart = ".fill" DispatchQueue.main.async { Task { try? await save.load() if !save.words.contains(suggestion.wrappedValue) { save.words.insert(suggestion.wrappedValue, at: 0) try? await save.save() } } } } else { heart = "" DispatchQueue.main.async { Task { try? await save.load() try? await save.delete(wordToDelete: suggestion.wrappedValue) try? await save.save() } } } done = true }, label: { Image(systemName: "heart" + (heart ?? "")) }) } }) ) { if suggestion.IPA.wrappedValue != "error" { CardView(wordSheet: suggestion) } } } } } Spacer() } } } #Preview { SearchView() }
Posted
by
Post marked as solved
1 Replies
498 Views
Hi, I want to add a SwiftData model to my Swift Playground in Xcode 15.2, but I get errors related to iOS version, has anyone encountered this? Thanks import Foundation import SwiftData struct testStruct: Identifiable { let id = UUID() var question: String var answer: String } @Model class testClass: Identifiable { let id = UUID() var question1: testStruct var question2: testStruct var question3: testStruct var question4: testStruct var question5: testStruct init(question1: testStruct, question2: testStruct, question3: testStruct, question4: testStruct, question5: testStruct) { self.question1 = question1 self.question2 = question2 self.question3 = question3 self.question4 = question4 self.question5 = question5 } }
Posted
by
Post not yet marked as solved
1 Replies
351 Views
Your app playground must be built with and run on Swift Playgrounds 4.4 or later (requires iPadOS 16 or macOS 13.5, or later) or Xcode 15 on macOS 13.5, or later. You may incorporate the use of Apple Pencil. If I want to develop a playground for the iPad and Apple Pencil, am I limited to using Playgrounds on iPadOS to make it? Or could I also use Playgrounds on macOS and Xcode? If I use Xcode to make my iPad playground, should I select "Xcode" for "Which software should we use to run your app playground?" I assume so, as I used Xcode to make my app — but then it will be run in a simulator by the judges, which means they cannot use the Apple Pencil. I'm a little lost here. Any guidance is appreciated.
Posted
by
Post not yet marked as solved
1 Replies
400 Views
I am making a code that uses pencilKit and you can draw on the canvas. However, I want to be able to detect if the resulted drawing is in contact with a Rectangle(). Is there any way to do this? I dont want to use variables for X and Y positions because I have more than 400 rectangles in a grid.
Posted
by
Post not yet marked as solved
2 Replies
585 Views
Hey Developers, I'm on the hunt for a new Apple laptop geared towards coding, and I'd love to tap into your collective wisdom. If you have recommendations or personal experiences with a specific model that excels in the coding realm, please share your insights. Looking for optimal performance and a seamless coding experience. Your input is gold – thanks a bunch!
Posted
by
Post not yet marked as solved
0 Replies
228 Views
Hi everyone, I just finished my first app and I have a doubt about whether picker view automatically makes a series of loops in its func. I put some prints inside the funcs and this is the result only when starting the view with the picker: Every time I select it the cycles continue. It's normal? Is there a way to avoid or control it? Thanks in advance for any response.
Posted
by
Post not yet marked as solved
0 Replies
453 Views
Is it possible to create SwiftData Document-based apps in App Playgrounds (or Swift Packages, since App Playgrounds are a special type of packages)? As explained in wwdc2023-10154, to create a document-based app you are required to provide an UTType that conforms to com.apple.package. This requires your file type to be declared and exported in the Info.plist file of an Xcode project, but App Playgrounds don't have them. Providing .package as a UTType seems to partially work: import SwiftUI import SwiftData @main struct SwiftDataFlashCardSample: App { var body: some Scene { #if os(iOS) || os(macOS) DocumentGroup(editing: Card.self, contentType: .package) { ContentView() } #else WindowGroup { ContentView() } .modelContainer(for: Card.self) #endif } } This way I am able to run the app, create and edit new document, and save it on disk. However, opening it again does not work (you cannot select it since it is a folder without a defined package type). Is there any workaround to this? I guess I could drop support for multiple documents entirely if this is not possible (I don't think this would affect my submission), but I would just like to check if there is any way to do this first.
Posted
by
Post not yet marked as solved
4 Replies
576 Views
Hello, Very recently, the following code has automatically appeared at the bottom of three of my SwiftUI View files: @available(iOS 17.0, macOS 14.0, tvOS 17.0, visionOS 1.0, watchOS 10.0, *) struct $s10Accent_Ace33_0BADA584A03144EFDAB57154E6FD3FBALl7PreviewfMf_15PreviewRegistryfMu_: DeveloperToolsSupport.PreviewRegistry { static let fileID: String = "Accent_Ace/HistoryView.swift" static let line: Int = 47 static let column: Int = 1 static func makePreview() throws -> DeveloperToolsSupport.Preview { DeveloperToolsSupport.Preview { let randomWord1 = FetchWord.getRandomWord() let randomWord2 = FetchWord.getRandomWord() @State var randomWords = [Word(word: randomWord1.0, IPA: randomWord1.1, lineNumber: randomWord1.2), Word(word: randomWord2.0, IPA: randomWord2.1, lineNumber: randomWord2.2)] HistoryView(words: $randomWords) } } } This is from one of my files but it's very similar in the other two. It seems to have something to do with my previews. The problem is that this code generates an error: Ambiguous use of 'init(_:traits:body:)'. My previews worked just fine before the auto-generated code appeared, so I tried deleting it. However, it automatically comes back no matter how many times I get rid of it. It's preventing me from building my App Playground, so I can't run the app or even see the previews. Does anyone know how to get rid of it or fix the error? Thanks for the help!
Posted
by
Post not yet marked as solved
0 Replies
325 Views
i have a simple code running on Xcode 15.2 and is showing blank in the liveView I am expecting to see Hello button in default blue , which navigates me to empty screen when tapped can someone helpe me why preview is not rendering properly? thank you so much
Posted
by
Post not yet marked as solved
1 Replies
348 Views
Hi guys! I want to know how can I create an array of UIImage elements and then access these elements randomly? I tried several times, but I have this issue: Can someone help me?
Posted
by
Post not yet marked as solved
7 Replies
867 Views
Hi Developers, I want to create a Vision app on Swift Playgrounds on iPad. However, Vision does not properly function on Swift Playgrounds on iPad or Xcode Playgrounds. The Vision code only works on a normal Xcode Project. SO can I submit my Swift Student Challenge 2024 Application as a normal Xcode Project rather than Xcode Playgrounds or Swift Playgrounds File. Thanks :)
Posted
by
Post marked as solved
2 Replies
473 Views
Hello, My App Playground uses a text file to work properly. I've had no issues running the app on Simulator, but it fails to find the file when being run on my physical iPhone. Has anyone had the same issue? Any idea what the problem is? Thanks for the help!
Posted
by
Post not yet marked as solved
2 Replies
280 Views
Thanks for zero replies. I can't believe that 28 to 51 people looked at my post and no one responded back. Anyway, I figured it out on my own after taking a break. I was just asking in so many words, where do I put the bold highlighted code. WHY NOT TRY app completed………. // // ContentView.swift // WhyNotTry // // Created by Geraldine Jones on 1/26/24. // import SwiftUI struct ContentView: View { var activities = ["Archery", "Baseball", "Basketball", "Bowling", "Boxing", "Cricket", "Curling", "Fencing", "Golf", "Hiking", "Lacrosse", "Rugby", "Squash"] var colors: [Color] = [.blue, .cyan, .gray, .green, .indigo, .mint, .orange, .pink, .purple, .red] ******** @State private var selected = "Baseball"******** @State private var id = 1 var body: some View { VStack { Text("Why not try...") .font(.largeTitle.bold()) VStack { Circle() .fill(colors.randomElement() ?? .blue) .padding() .overlay( Image(systemName: "figure.\(selected.lowercased())") .font(.system(size: 144)) .foregroundColor(.white) ******** .transition(.slide)******** ******** .id(id)******** ) Text("\(selected)!") .font(.title) } Spacer() Button("Try again") { ****** withAnimation(.easeInOut(duration: 1))****** { selected = activities.randomElement() ?? "Archery" ********id += 1******** } } .buttonStyle(.borderedProminent) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Posted
by
Post not yet marked as solved
1 Replies
254 Views
I've written the code exactly the way the tutorial explained. Word for word. The tutorial states to write @State var selected = "Bowling" but that doesn't work. I asked for help before but no one replied. So I thought I would post again with the code.
Posted
by