Post

Replies

Boosts

Views

Activity

HelloTriangle in Swift: error about depth attachment pixel format
Hi,I'm trying to port this to Swift. https://developer.apple.com/documentation/metal/hello_triangleTo get it to run I had to add the following line to the renderer class. Any idea why it's not needed in the Objective-C version? pipelineStateDescriptor.depthAttachmentPixelFormat = metalView.depthStencilPixelFormatWithout it I get an error: -[MTLDebugRenderCommandEncoder validateFramebufferWithRenderPipelineState:]:1232: failed assertion `For depth attachment, the render pipeline's pixelFormat (MTLPixelFormatInvalid) does not match the framebuffer's pixelFormat (MTLPixelFormatDepth32Float).'Rob
3
0
5.8k
Dec ’21
How does SwiftUI update if objectWillChange fires *before* change
I'm wondering how SwiftUI updates work in connection with ObservableObjects. If a SwiftUI View depends on an `ObservableObject`, the object's `objectWillChange` publisher fires, and SwiftUI learns about the change, before the change happens. At this point, SwiftUI can't re-render a View, right? Because the new properties aren't there yet. So what does SwiftUI do? Does it schedule the change for later? That doesn't make sense either - how can it know when the object will be ready to be used in a new rendering of the UI? ~ Rob
3
0
5.4k
Feb ’22
Too many empty "required" UIView.init(coder:) methods
Hi,I have a lot of UIViews where the compiler forces me to add an init(coder:) initializer, like this:class FooView : UIView /* or a UIView subclass */ { ... required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } ... }It claims it's required but my program runs fine without it. I do not create the views from an archive.This makes me wonder if something is wrong here with the design of the library, or the concept of a 'required' initializer. What do people think? Does it make sense or is this a wart? If so, can it be fixed?Rob
Topic: UI Frameworks SubTopic: UIKit Tags:
5
1
2.8k
Sep ’21
Can't run unit tests with Xcode 12.5. Code signing?
After updating to 12.5, I now get an error trying to run my unit tests. This is for a macOS app. dyld: warning: could not load inserted library '/[...]/DerivedData/[...]/Contents/Frameworks/libXCTestBundleInject.dylib' into hardened process because no suitable image found.  Did find: /[...]/libXCTestBundleInject.dylib: code signature in (/[...]/libXCTestBundleInject.dylib) not valid for use in process using Library Validation: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?) Anyone else face and fix this, or understand what it is? I changed the "Signing Certificate" in my test target to "Sign to Run Locally" (from "Development") to see if that would help. It didn't fix it.
3
0
4.6k
Jun ’21
Can't use protocols with SwiftUI models?
I've been using protocols to help model a hierarchy of different object types. As I try to convert my app to use SwiftUI, I'm finding that protocols don't work with the ObservableObject that you need for SwiftUI models. I wonder if there are some techniques to get around this, or if people are just giving up on "protocol oriented programming" when describing their SwftUI models? There is example code below. The main problem is that it seems impossible to have a View that with an model of protocol `P1` that conditionally shows a subview with more properties if that model also conforms to protocol `P2`.For example, I'm creating a drawing/painting app, so I have "Markers" which draw on the canvas. Markers have different properties like color, size, shape, ability to work with gradients. Modeling these properties with protocols seems ideal. You're not restricted with a single inheritance class hierarchy. But there is no way to test and down-cast the protocol...protocol Marker : ObservableObject { var name: String { get set } } protocol MarkerWithSize: Marker { var size: Float { get set } } class BasicMarker : MarkerWithSize { init() {} @Published var name: String = "test" @Published var size: Float = 1.0 } struct ContentView<MT: Marker>: View { @ObservedObject var marker: MT var body: some View { VStack { Text("Marker name: \(marker.name)") if marker is MarkerWithSize { // This next line fails // Error: Protocol type 'MarkerWithSize' cannot conform to 'MarkerWithSize' // because only concrete types can conform to protocols MarkerWithSizeSection(marker: marker as! MarkerWithSize) } } } } struct MarkerWithSizeSection<M: MarkerWithSize>: View { @ObservedObject var marker: M var body: some View { VStack { Text("Size: \(marker.size)") Slider(value: $marker.size, in: 1...50) } } }Thoughts?
3
1
9.4k
Sep ’21
Wrapped UIActivityViewController is blank on first showing
Here's the entire app below. On iOS 15, it pops up blank. If you dismiss it and click "Share" again, then it looks right. Is this a bug, or is the code wrong? struct ContentView: View {     @State private var showShare = false     @State private var shareItems: [Any] = []     var body: some View {         VStack {             Text("Test ActivityViewController")             Button("Share") {                 share()             }.sheet(isPresented: $showShare) {                 print("dismissed")             } content: {                 ActivityViewController(activityItems: shareItems)             }         }     }     func share() {         shareItems = ["test"]         showShare = true     } } struct ActivityViewController: UIViewControllerRepresentable {     let activityItems: [Any]     func makeUIViewController(context: Context) -> UIActivityViewController {         let c = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)         return c     }     func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {} }
0
1
725
Sep ’21
Simple layout still fails
I'm surprised this simple code still doesn't work on iOS 13.3 / Xcode 11.3. On my iPhone SE it's almost all off screen.It's just two pieces of text, side by side, and two pickers, side by side. Anyone know a workaround? struct ContentView: View { @State var choice: Int = 10 @State var choice2: Int = 10 var body: some View { return VStack { HStack { Text("Some text here") Spacer() Text("Foo baz") } HStack { Picker(selection: self.$choice, label: Text("C1")) { ForEach(0..<10) { n in Text("\(n) a").tag(n) } } Picker(selection: self.$choice2, label: Text("C2")) { ForEach(0..<10) { n in Text("\(n) b").tag(n) } } } } } }
4
1
4k
May ’22
Upgrading app's UIDocument format from Data to FileWrapper?
Hi,I had a document-based iOS app working, but want to change it so it saves to a package. Seems like it's better when big chunks of a file may not be changing. In Xcode, under the Target > Info > Exported UTI > Conforms To, I had: "public.data, public.content". If I change that to "com.apple.package", then I can't open my old files to upgrade them. But if I *add* "com.apple.package", then the app opens both kinds as desired. I wonder if having it conform to all three of those types is going to cause other problems.Rob
Topic: UI Frameworks SubTopic: UIKit Tags:
3
0
1.5k
Jul ’21
Still wondering about objectWillChange (vs objectDidChange) magic :)
Hi all, The WWDC video offers (at about 16:45) as short explanation as to why it's "objectWillChange" instead of "objectDidChange". He said it's because SwiftUI needs to coalesce the changes. Okay, but then how does it know when the changes have ended? It seems like you'd need two events. Something like: self.objectWillChange.send() self.foo = ... self.bar = ... self.objectHasFinishedChanging.send() or self.objectChanges { 		self.foo = ... 		self.bar = ... }
4
0
2.5k
Feb ’21
SKTestSession failTransactionsEnabled not working
If I purchase a product with a test session in my unit test, everything works as expected. I see a purchased transaction on my payment queue. But if I set the property to make it fail, nothing happens. Shouldn't I observe a transactions with transactionState == .failed?let session = try! SKTestSession(configurationFileNamed: "Configuration") session.disableDialogs = true session.clearTransactions() session.failTransactionsEnabled = true session.failureError = .unknown session.buyProduct(productIdentifier: productID) Has anyone used this? This observer normally gets called. But not when I set failTransactionsEnabled.    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {     
1
0
832
Mar ’21
SwiftUI bug: Alert shows twice?
I'm running this on macOS. I looks like a bug to me. If I activate the menu item and confirm the alert, the alert pops up again. It only double-shows once; then it behaves correctly. In my real app, it double-shows every time. If I uncomment that DispatchQueue.main.async, it "fixes" it. macOS 11.2.3, Xcode 12.4. swift @main struct DoubleAlertApp: App {     @State var showAlert: Bool = false     @StateObject var model: Model = .init()     var body: some Scene {         WindowGroup {             ContentView().environmentObject(model)                 .background(EmptyView()                     .alert(isPresented: $showAlert) {                          Alert(title: Text("Test"),                                message: Text("This will do something"),                                primaryButton: .cancel(),                                secondaryButton: .destructive(Text("Do it"), action: confirmedAction))                     })         }.commands {             CommandGroup(replacing: CommandGroupPlacement.newItem) {                 Button(action: testAlert) {                     Text("Test Alert")                 }.keyboardShortcut("t")             }         }     }     private func testAlert() {         showAlert = true     }     private func confirmedAction() {         print("confirmedAction")         // DispatchQueue.main.async {             self.model.change()         //}     } } class Model: ObservableObject {     init() {}     @Published var foo: Int = 0     func change() {         objectWillChange.send()         foo += 1     } } struct ContentView: View {     @EnvironmentObject var model: Model     var body: some View {         Text("Hello. \(model.foo)").padding()     } }
2
0
2.3k
Mar ’21
Hierarchical List / OutlineGroup - can't change data?
Does anyone use the new hierarchical data List (ie, OutlineGroup) with a model where the tree data changes? I'm on Big Sur beta. I have code like this: List([treeRoot], children: \.children) { item in ... Say the treeRoot (observed object) gets a new child. The view tries to re-render and fails: 2020-09-21 ... [General] NSOutlineView error inserting child indexes <_NSCachedIndexSet: 0x600000760000>[number of indexes: 1 (in 1 ranges), indexes: (3)] in parent 0x0 (which has 1 children).
1
0
807
Feb ’22
UIDocument no longer saving, error in URLByAppendingPathExtension
I've been working on an iOS app with UIDocuments. They were saving fine. Now all of a sudden, after unrelated changes, nothing will save. Here is the error printed in Xcode console: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL URLByAppendingPathExtension:]: component, components, or pathExtension cannot be nil.' log.debug("save to:\(self.document.fileURL)") document.save(to: document.fileURL, for: .forOverwriting) { success in ... } The log message there prints a valid URL.
Topic: UI Frameworks SubTopic: UIKit Tags:
2
0
1.1k
Mar ’22
StoreKit AppStore.sync throws userCancelled when there is no network
I have a button to restore purchases in my app. It calls AppStore.sync() as suggested by sample code. I'm testing in the sandbox, I put my device in airplane mode, and it throws StoreKitError.userCancelled. That's odd. Anyone else see this? I'd like to show an error alert popup to the user here, but I can't differentiate between this an a real userCancelled.
1
1
1.5k
Apr ’23
MagnificationGesture needs location?
I tried to replace UIKit's UIPinchGestureRecognizer with SwiftUI's MagnificationGesture, but it doesn't seem possible in my case. I use the location(in: UIView) function from the former, which allows me to zoom in on that point, specifically. It's a better experience when zooming in on an image. Can I get that info from the MaginificationGesture? In the example code I see only the CGFloat for the amount of magnification.
0
1
545
Oct ’21