I am making an iPhone-first app which has a 2 level data structure. I want the user to be able to drag List rows from section to section, but not reorder the sections. Is there a SwiftUI way to do it, or should I resort to UIKit?
The basic problem seems to be that ForEach.onMove only allows reordering within its nearest datasource. That seems sensible as a general facility.
As it stands now drags can only happen within a section.
Swift
ForEach(groups) { group in
Section(header: Text(group.text)) {
ForEach(group.items) { item in
Text(item.text)
}
}
}
.onMove { … }
I might be willing to dive into UIKit to get this done, if it'll handle it. Right now I've flattened the data and marked some items as "containers" and others as "leaves". All get emitted as a dumb flat list:
Swift
ForEach(items) { item in
if item.isContainer {
Text(item.text).bold()
}
else {
Text(item.text)
}
}
.onMove { … }
The major downside is users can move the container "section header" lines.
Drag and drop doesn't seem to work on iPhone, just iPads. I'm kinda shy about hierarchical lists using List(_,children:) because I expect move would still allow top level items (my containers) would be allowed to be moved.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I've got Yet Another Protocol Question. Sorry, folks.The Swift 5.1 manual describes creating a `Collection` where the `Element` is a simple protocol, but doesn't explain how to make a Collection where the Element is a protocol with an associatedtype. In my case it's a protocol `Playable` that requires conformance to `Identifiable`.I am fine with requiring the `Identifiable.ID` type to be `Int` for all types which adopt `Playable`, but I don't know how to express that qualification/requirement. The bits hit the fan when I try to declare something to be `[Playable]`.My playground code might make my question clear.protocol Playable: Identifiable
// DOESN'T WORK where ID: Int
{
// DOESN'T HELP associatedtype ID = Int
// DOESN'T HELP var id: Int { get }
func play()
}
struct Music: Playable {
var id: Int
func play() { print("playing music #\(id)") }
}
(Music(id: 1)).play() // displays: "playing music #1\n"
class Game: Playable {
var id: Int
init(id: Int) {
self.id = id
}
func play() { print("playing game #\(id)") }
}
(Game(id: 2)).play() // displays: "playing game #2\n"
enum Lottery: Int, Playable {
case state = 100
case church
case charity
var id: Int {
return self.rawValue
}
func play() { print("playing lottery \(self) #\(self.rawValue)") }
}
Lottery.church.play() // displays: "playing lottery church #101\n"
var stuff: [Playable] = [] // error: Protocol 'Playable' can only be used as a generic constraint because it has Self or associated type requirements
stuff.append(Music(id: 10))
stuff.append(Game(id: 24))
stuff.append(Lottery.charity)
stuff.map { $0.id }My goal is to have different structs and classes conforming to Playable (and hence to Identifiable) able to live inside a Collection.
Is there a variant of TextEditor that works with AttributedString? Does it expose the selectedText range?
I want to create a custom text editor to mark ranges of an AttributedString. But I can make do in a clunky way with just String if I at least can get the selectedRange of the text in TextEditor.
I expect I'll need to go to UIKit and use UITextView.
The keyboard shortcut Control + Command + F normally toggles a window's full screen mode. It's assigned to the menu command View / Enter Full Screen. Well, if you make a multiplatform document-based app, create a new document, the shortcut does not work. The menu command works just fine.
Does anyone have a workaround for this?
This looks like a refresh of an old question. I'm using iOS 15 beta 7 and have presented a UIActivityViewController from a SwiftUI app. I get a ton of these errors when trying to share a two-item list containing String and UISimpleTextPrintFormatter.
[default] LaunchServices: store (null) or url (null) was nil: Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=264, _LSFunction=-[_LSDReadClient getServerStoreWithCompletionHandler:]}
[default] Attempt to map database failed: permission was denied. This attempt will not be retried.
[db] Failed to initialize client context with error Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=264, _LSFunction=-[_LSDReadClient getServerStoreWithCompletionHandler:]}
[default] -imageForImageDescriptor: can do IO please adopt -imageForDescriptor: for IO free drawing or -prepareImageForDescriptor: if IO is allowed. (This will become a fault soon.)
[default] LaunchServices: store (null) or url (null) was nil: Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={NSDebugDescription=process may not map database, _LSLine=264, _LSFunction=-[_LSDReadClient getServerStoreWithCompletionHandler:]}
It looks as if the API is checking for entitlements I haven't requested, but I am not trying to share images. I just want to share text as plaintext or a nicely formatted printable attributed string.
How can I tell List to animate row height changes?
I have a list whose rows may grow or shrink with user actions. When that happens the List is redrawn with the new heights instantly but the contents slide to their new position. It'd be better if the row heights were animated. Since I don't know what a row's height is I can't use the usual .frame(height: self.animate ? 60 : 90)
This code demonstrates the problem.
struct ContentView: View {
@State private var numbers: [Int] = [0,1,2,3]
var body: some View {
VStack {
List {
Item(numbers: $numbers)
Item(numbers: .constant([9,8,7]))
}
.font(.largeTitle)
HStack {
Button { withAnimation { addNumber() }}
label: { Text("Add") }
Spacer()
Button { withAnimation { removeNumber() }}
label: { Text("Remove") }
}
}
.padding()
}
private func addNumber() {
numbers.append(numbers.count)
}
private func removeNumber() {
numbers = numbers.dropLast()
}
}
struct Item: View {
@Binding var numbers: [Int]
var body: some View {
VStack {
ForEach(numbers, id:\.self) { n in
Text("\(n)")
}
}
}
}
When I open the "devices and simulators" window now I only see "No selection" in the center. No sidebar pane, and no detail pane. I was able to set up some simulators up to last week or so, and now this. I've no idea how to create a new simulator or inspect the ones I have.
Topic:
Developer Tools & Services
SubTopic:
Xcode
I want to access to a small number of Markdown text files. It looks like the asset catalog feature "Folder with Namespace" might do well, as I could store these small files in a folder that the asset catalog contains. How would I go about getting the string contents of a particular file if I know its name?
I made a subclass of UICollectionViewCell and Swift is complaining that I'm not allowed to use superclass properties like bounds, backgroundView or selectedBackgroundView. This very code was given by Appleʼs documentation - https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/changing_the_appearance_of_selected_and_highlighted_cells so I don't understand why it's disallowed.
I declared class MyCollectionViewCell: UICollectionViewCell method awakeFromNib.
class MyCollectionViewCell: UICollectionViewCell {
...
override class func awakeFromNib() {
...
let redView = UIView(frame: bounds)
redView.backgroundColor = colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
self.backgroundView = redView
let blueView = UIView(frame: bounds)
blueView.backgroundColor = colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)
self.selectedBackgroundView = blueView
Xcode 12.2 gives an error about bounds, backgroundView, and selectedBackgroundView saying stuff like "Instance member 'bounds' cannot be used on type 'MyCollectionViewCell'".
If I declare a variable as UICollectionViewCell I can set these properties in it, but a function in a subclass of UICollectionViewCell cannot access its own properties?
I want my app to receive certain data types shared from other apps. I'm interested in text and URLs today, and maybe images later. UIActivity seems to be the way to start but I don't know what to do with the subclass I've created.
I assume it at least needs to be declared in the app's properties, but I don't know where to read about that and nothing stands out in the project editor. I don't know the API or keywords to do my research, so if anyone can point me I'll appreciate it.
Using CloudKit, when I perform CKFetchDatabaseChangesOperation(previousServerChangeToken:) the response in fetchDatabaseChangesCompletionBlock is an error:
Metasync Continuation could not properly be parsed
The first time through this works when the token is nil. The second time through it fails with this error. It was working at one time.
I've tried deleting the app and resetting the development database as well.
I am guessing this has to do with the server change token. I save and restore the server change token to UserDefaults using NSKeyedArchiver to archive/unachive it as Data, so it should be perfectly preserved. I'm using the privateCloudDatabase with a non-default zone.
To implement row reordering I know I could use List{ForEach{}.onMove} but in my situation I can't use List for reasons. So I need to implement my own item reordering using onDrag and onInsert.
These modifiers use NSItemProvider. I think therefore my dragged data type needs to implement NSItemProviderWriting (and NSItemProviderReading). I've looked for examples but the closest code I've found is dragging URLs. When I try to implement these protocols in my type I end up with an error in .onInsert at (NSItemProvider item).loadObject(ofClass:MyType.self) that says "Instance method 'loadObject(ofClass:completionHandler:)' requires that 'MyType' conform to '_ObjectiveCBridgeable'"
How should I be using .onDrag and .onInsert with a custom type?
I've been building my app on Xcode 13 when suddenly it doesn't know about the iOS 15 APIs. Here are a couple error examples:
self.modified = Date.now
// Type 'Date' has no member 'now'
and
operation.modifySubscriptionsResultBlock = { result in
// Value of type 'CKModifySubscriptionsOperation' has no member 'modifySubscriptionsResultBlock'
I can take the exact same code and build it on my other Mac and it builds properly. Both Macs are using Xcode Version 13.0 (13A233) and running macOS 11.6 (20G165). I checked the deployment info for project and target (iOS 15.0), but of course using git I know I have the exact same code base on both machines.
Is there an Xcode preference or system file that got hosed? I tried reinstalling Xcode, but it didn't help.
I am writing a document-based app for macOS using SwiftUI. I want the File menu's New Document command to show a template picker/wizard, and then let the wizard create the document.
How do I structure this? Is there documentation? Examples?
I tried this pattern
@main struct DocDemoApp: App {
var body: some Scene {
WindowGroup { NewDocWizard() }
DocumentGroup(newDocument: { DocDemoDocument() }) {
ContentView(document: $0.document)
}
}
}
The NewDocWizard calls newDocument({ DocDemoDocument() }). But the WindowGroup makes a File > New Window command while DocumentGroup makes the File > New Document command. I need just New Document and it should show the NewDocWizard.
.modelContainer(for: MyMode.self, isUndoEnabled: true)
This may work for single model containers, but I have a number of models. I don't see how to enable undo for multiple model containers.