Post

Replies

Boosts

Views

Activity

SwiftUI, macOS, how to hook up to Edit menu's commands?
In SwiftUI on macOS, you can add items to the main menu by using things like CommandGroup, CommandMenu. But the default menus already have items. For example, the Edit menu has Undo, Redo, Cut, Copy, Paste, Delete, Select All. Those menu items are grayed out and don't do anything. Is there a way to hook some Swift code to these? Or do you just use CommandGroup(replacing: ...) to replace them? That doesn't seem right; why put them there if you just have to replace them? Besides hooking up a function to run when they get clicked, I'd like to know how to enable and disable them depending on app state.         WindowGroup {             MyContentView()         }.commands {             SidebarCommands()             CommandGroup(after: .newItem) {                 Button { newFolder() } label: { Text("New Folder") }                     .keyboardShortcut("n", modifiers: [.command, .option])             }         }
1
0
2.5k
Sep ’22
For cursor update events (with NSTrackingArea) how to know if it's coming or going?
I've added an NSTrackingArea to my NSView because I want a certain rectangular area to show a different cursor. As expected, my view gets a call to it's cursorUpdate:(NSEvent*) method, but how do I tell whether it's an "enter" or "leave". - (void)cursorUpdate:(NSEvent *)event { // Do I push or pop my custom NSCursor? } I notice the event.modifierFlags changes from 8 to 9. But I don't see any public enum constants to test that, so I don't know if I can depend on that. The public enum contains stuff like this, in the higher bits. typedef NS_OPTIONS(NSUInteger, NSEventModifierFlags) { NSEventModifierFlagCapsLock = 1 << 16, NSEventModifierFlagShift = 1 << 17, ... The tracking area setup code: NSRect nsRect = ... NSTrackingAreaOptions options = NSTrackingCursorUpdate | NSTrackingActiveInKeyWindow; NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect: nsRect options: options owner: owner userInfo: userInfo]; [myView addTrackingArea: trackingArea];
Topic: UI Frameworks SubTopic: AppKit Tags:
1
0
1.5k
Oct ’22
simctl launch --console flag doesn't seem to work?
I created a simple app in Xcode. Installed and ran it in the iOS Simulator. I can also start it from command line like this: % xcrun simctl launch booted com.example.TestBuildCommands --console com.example.TestBuildCommands: 52877 % It just prints that one line and returns my shell prompt. But the help for launch says that --console should: "Block and print the application's stdout and stderr to the current terminal." In my main() function I have: int main(int argc, char * argv[]) { printf("In main.\n"); ... Shouldn't I be seeing that message in my terminal screen? % xcrun simctl help launch Launch an application by identifier on a device. Usage: simctl launch [-w | --wait-for-debugger] [--console|--console-pty] [--stdout=<path>] [--stderr=<path>] [--terminate-running-process] <device> <app bundle identifier> [<argv 1> <argv 2> ... <argv n>] --console Block and print the application's stdout and stderr to the current terminal. Signals received by simctl are passed through to the application. (Cannot be combined with --stdout or --stderr) [...] ps. Anyone know how to turn off syntax highlighting in those triple-backquoted code blocks that are meant to be just terminal text, not highlighted code?
1
1
1.3k
Apr ’23
App compiles but "Unable to install" on device
When I try to run my app on my iPhone, from Xcode, I get a popup that says Unable to Install "AppName". There is some text in the popup. Here's the first part of it. (I replaced the real app's name with "AppName".) Anyone know how to fix this? Unable to install "AppName" Domain: com.apple.dt.MobileDeviceErrorDomain Code: -402653103 User Info: { DVTErrorCreationDateKey = "2024-09-28 04:04:29 +0000"; IDERunOperationFailingWorker = IDEInstalliPhoneLauncher; } -- Unable to install "AppName" Domain: com.apple.dt.MobileDeviceErrorDomain Code: -402653103 -- Could not inspect the application package. Domain: com.apple.dt.MobileDeviceErrorDomain Code: -402653103 User Info: { DVTRadarComponentKey = 282703; MobileDeviceErrorCode = "(0xE8000051)"; "com.apple.dtdevicekit.stacktrace" = ( ...
1
0
396
Sep ’24
Equivalent of coalescedTouchesForTouch in AppKit?
This method on UIEvent gets you more touch positions, and I think it's useful for a drawing app, to respond with greater precision to the position of the Pencil stylus. Is there a similar thing in macOS, for mouse or tablet events? I found this property mouseCoalescingEnabled, but the docs there don't describe how to get the extra events.
Topic: UI Frameworks SubTopic: AppKit Tags:
1
0
178
Aug ’25
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
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
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
Can't interpolate a Bool in SwiftUI Text?
Simple code like this gives an error. struct MyView: View {     @State private var test: Bool = false     var body: some View {           Text("Hello. \(test)") The error: Instance method 'appendInterpolation(_:formatter:)' requires that 'Bool' inherit from 'NSObject' What is going on?
2
1
3.9k
Sep ’21
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
Combining chars do not render right in some fonts
Here's a simple demo. I run it on macOS 12.1, compiled with Xcode 13.2. struct ContentView: View {     var body: some View {         VStack {             Text("ee")             Text("eé") Text("e\u{E9}") // "e with acute"             Text("ee\u{301}") // "combining acute"         }.font(.custom("Avenir", fixedSize: 18))          .padding(20)     } } In the 4rd one, the "e" is rendered in the wrong size/font. Screenshot: Other fonts do not have the problem. For example, "Avenir Next" and "Helvetica". Is there a way (in code) to tell which fonts can handle combining chars? Is this a bug? I notice the same thing happens when I use Core Text to draw the strings at a low level. So it's not just SwiftUI. In TextEdit, if have Avenir font, type "option-e" + "e" I get a nice letter. Maybe TextEdit is doing what Xcode did in the second line, and using the "e with acute" unicode character.
2
0
767
Feb ’22
CustomMetalView sample uses deprecated functions - update?
The sample code here, has code like: // Create a display link capable of being used with all active displays cvReturn = CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink); But that function's doc says it's deprecated and to use NSView/NSWindow/NSScreen displayLink instead. That returns CADisplayLink, not CVDisplayLink. Also the documentation for that displayLink method is completely empty. I'm not sure if I'm supposed to add it to run loop, or what, after I get it. It would be nice to get an updated version of this sample project and/or have some documentation in NSView.displayLink
2
0
362
Jul ’25