Construct and manage a graphical, event-driven user interface for your macOS app using AppKit.

Posts under AppKit tag

189 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Whats the Appkit equivalent of SwiftUI's NavigationSplitView?
How do I implement the same Navigation split view with a side bar in Appkit? Basically I have this code: import SwiftUI struct ContentView: View { var body: some View { NavigationSplitView { // Sidebar List { NavigationLink("Item 1", value: "Item 1 Details") NavigationLink("Item 2", value: "Item 2 Details") NavigationLink("Item 3", value: "Item 3 Details") } .navigationTitle("Items") } content: { // Main content (detail view for selected item) Text("Select an item to see details.") .padding() } detail: { // Detail view (for the selected item) Text("Select an item from the sidebar to view details.") .padding() } } } struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } } and wanted to somehow convert it to Appkit. I tried to use an NSSplitViewController but I still don't have that side bar and that button to collapse it, how do I go about this?
1
0
65
8h
NSTextField Delegates Not Triggering After Refactoring NSView to NSViewController in macOS App
I'm developing a macOS application and facing an issue with NSTextField delegates after refactoring my code. Here's the situation: I have an NSWindowController. Inside the NSWindowController, there's a container NSView named containerView. On top of containerView, I added a custom NSView subclass named MyDetailsView. MyDetailsView has two NSTextField instances, and their delegates are properly set. The delegate methods like controlTextDidChange(_:) were getting called as expected. Due to some additional requirements, I refactored MyDetailsView into MyDetailsViewController, a subclass of NSViewController. I created a corresponding .xib file for MyDetailsViewController. Updated the code to load and add MyDetailsViewController's view (view property) to containerView. Verified that the NSTextField delegates are still being set, and the fields are displayed correctly in the UI. However, after this refactor, the NSTextField delegate methods (e.g., controlTextDidChange(_:)) are no longer being triggered. **What I've Tried: ** Verified that the delegates for the NSTextField instances are correctly set after the refactor. Ensured that the MyDetailsViewController's view is added to containerView. Question: What could be causing the NSTextField delegate methods to stop working after refactoring from NSView to NSViewController? @IBOutlet weak var customeView: NSView! var myDetailsViewController: MyDetailsViewController! var myDetailsView: MyDetailsView! var isViewController: Bool = true override func windowDidLoad() { super.windowDidLoad() if isViewController { myDetailsViewController = MyDetailsViewController(nibName: "MyDetailsViewController", bundle: nil) self.customeView.addSubview(myDetailsViewController.view) } else { myDetailsView = MyDetailsView.createFromNib() self.customeView.addSubview(myDetailsView!) } } override func showWindow(_ sender: Any?) { super.showWindow(nil) window?.makeKeyAndOrderFront(nil) } override var windowNibName: NSNib.Name? { return NSNib.Name("MyWindowController") }} class MyDetailsViewController: NSViewController { @IBOutlet weak var textField: NSTextField! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } } extension MyDetailsViewController: NSTextDelegate { func controlTextDidChange(_ obj: Notification) { guard let textField = obj.object as? NSTextField else { return } print("The value is ----> (MyDetailsViewController) \(textField.stringValue)") } } TextField delegate is set in XIB.
0
0
70
1d
Metal-cpp-extensions isn't working inside frameworks
I am making a framework in C++ using metal-cpp, basically a small game engine. I am also consequently using metal-cpp-extensions provided in LearnMetalCPP to make applications work. For one of my classes, I needed to add AppKit.hpp inside a public header file, so I moved it and its associate headers(NSApplication.hpp, NSMenu.hpp, etc.) from Project headers to Public in Build Phases' Headers, however, it started giving me the error "cast of C pointer type 'void *' to Objective-C pointer type 'Class' requires a bridged cast" at several points in the AppKit headers. They don't appear when AppKit and its associates are in the Project headers, or when they are in the Private headers and no headers import it. I imagined that disabling Objective-C ARC and Using __bridge casts outside of ARC in Build Settings would solve it, but it didn't budge. I imagined it wouldn't involve actively changing the headers would be the answer, but even if I try to put __bridge before the problematic casts, it didn't recognize __bridge. How do I solve this? And why is it only happening in Public and not Project headers?
1
0
137
6d
Bug when entering credentials for a Mac on LAN through File -> Open... -> Network
I've been experiencing a bug when trying to open a file on a remote machine through File -> Open... -> Network -> Connect As... where the Name/Password dialog won't let me enter more than one character into its text fields. I'm able to get one more character in by toggling between the "Registered User" and "Guest" radio buttons, and it seems to fix itself entirely when I focus on another window before entering my credentials. Once it is "fixed", it doesn't happen again until the machine's restarted. I was able to reproduce this on 15.1 and 15.1.1, but not on 15.0.1 (I do not currently have access to a machine running 15.2). Here are some reproduction steps: (You will need a shared computer on LAN) Restart your machine (un-check reopen windows when logging back in) Open TextEdit From the Menu Bar, click “File > Open...” Select “Network” from the Open Dialog’s sidebar Select your shared computer on LAN and click “Connect As…” Try typing in the password field. This will only allow the first key press to produce a character in the text field. (In my case, the Name field was already populated, so the password field was automatically selected) (Filed as FB16039397)
0
0
125
1w
Screen record restriction in MacOS app
I have a MacOs AppKit app. This app we are developing for examination purposes. We dont want the user to screen record and also to take screen shot. We created a window and set the sharingType to none. also we have set window.level to CGShieldingWindowLevel() Below is the code if let window = NSApp.windows.first { window.title = "Test" window.sharingType = .none // Disable screen capture and recording window.level = NSWindow.Level(rawValue: Int(CGShieldingWindowLevel())) // } As per documentation the windows should be excluded from screen capture and also recording But the window is excluded only from screen capture and not from screen recording. Please give us a solution to prevent screen recording in MacOs native app.
3
0
146
1w
NSOutlineView with Diffable Data Source
Hi, On macOS, there seems to be a NSTableViewDiffableDataSource and an NSCollectionViewDiffableDataSource, but there seems to be nothing for NSOutlineView. Is it possible to somehow use NSTableViewDiffableDataSource with NSOutlineView that I'm missing? If not, is it possible to use NSTableView with NSTableViewDiffableDataSource to show a 'table' with section headers?
5
0
211
5d
Dock tile plugin and app groups
In one of my apps I use an app group to share data between the app and a command line tool. This works as expected. The app also contains a Dock Tile plugin and I wonder if there's a way to access the group container from this plugin? Thanks in advance for your help. Best regards, Marc
1
0
128
2w
Changing the font size of a row - view-base tableview
So I'm following this code here where I'm using a tableview to display the files contained in a folder along with a group cell to display the name of the current folder: Here's my tableView:isGroupRow method: method which basically turns every row with the folder name into a group row (which is displayed in red in the previous image ). -(BOOL)tableView:(NSTableView *)tableView isGroupRow:(NSInteger)row { DesktopEntity *entity = _tableContents[row]; if ([entity isKindOfClass:[DesktopFolderEntity class]]) { return YES; } return NO; } and here's my tableView:viewForTableColumn:row: method where I have two if statements to decide whether the current row is a group row (meaning it's a folder) or an image: -(NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row; { DesktopEntity *entity = _tableContents[row]; if ([entity isKindOfClass:[DesktopFolderEntity class]]) { NSTextField *groupCell = [tableView makeViewWithIdentifier:@"GroupCell" owner:self]; [groupCell setStringValue: entity.name]; [groupCell setFont:[NSFont fontWithName:@"Arial" size:40]]; [groupCell setTextColor:[NSColor magentaColor]]; return groupCell; } else if ([entity isKindOfClass:[DesktopImageEntity class]]) { NSTableCellView *cellView = [tableView makeViewWithIdentifier:@"ImageCell" owner:self]; [cellView.textField setStringValue: entity.name]; [cellView.textField setFont:[NSFont fontWithName:@"Impact" size:20]]; [cellView.imageView setImage: [(DesktopImageEntity *)entity image]]; return cellView; } return nil; } Now, if the current row is an image, I change its font to Impact with a size of 40 and that works perfectly, the problem here is with the first IF statement, for a group row I wanted to change the font size to arial with a size of 40 with a magenta color but for some reason I can only get the color to work: You can see that my changes to the font size didn't work here, what gives? How can I change the font size for the group row ?
0
0
200
Nov ’24
NSToolbarItemGroup dynamically update subitems in toolbar
Developing on Monterey 12.7.5 I'm having trouble with updating subitems on NSToolbarItemGroup when selecting the item directly from the NSToolbar items array. I select the group item off the items array on the toolbar, and then call setSubitems: on the item, with a new array of NSToolbarItems. The group item disappears from the toolbar. It seems to leave a blank invisible item in the toolbar taking up space. I can't manually reinsert the item into the toolbar until I drag out the blank item, then drag back in the real item. Once dragged back in from the palette it displays correctly. The workaround I've come up with is to remove the item with NSToolbar removeItemAtIndex: and reinsert it with NSToollbar insertItemWithItemIdentifier:atIndex:. This works to update the subitems. Every other toolbar item property that I've tried has been able to update the item directly in the toolbar. It's only the group item's subitems that don't want to update correctly. Is there a correct way to do this that I'm missing? Calling [toolbar validateVisibleItems] didn't seem to help.
0
0
179
Nov ’24
Prevent macOS window.level floating from showing on all screens in a multi monitor setup?
I am using the window.level set to .floating as described here: https://developer.apple.com/documentation/appkit/nswindow/level The setting itself works okay. However, in a multi monitor setup, the floating window is appearing on both the screens. How can I prevent this? My users report that before macOS Sonoma, this used to not happen. Has this behaviour changed? How can I revert back to the old behaviour?
1
0
239
Nov ’24
Crash when setting up the content view loaded from a NIB
I am trying to understand why I am seeing crash reports for my code that creates a view from a NIB like the code below. The crash occurs when referencing contentView which should have been bound when the NIB was loaded. Am I missing something here other than checking the result of the loadNibNamed function call? class MyView: NSView { @IBOutlet var contentView: NSView! init() { super.init(frame: NSRect(x: 0, y: 0, width: 84.0, height: 49.0)) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { Bundle.main.loadNibNamed("MyView", owner: self, topLevelObjects: nil) translatesAutoresizingMaskIntoConstraints = false contentView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentView) contentView.frame = self.bounds }
6
0
418
Nov ’24
App that runs fine under Xcode 15 does not work on Xcode 16.
When I upgraded to Sequoia 15.1, an app that worked fine under OS 14 stopped working. Out of 4 views on the main screen, only 1 is visible. Yet, if I click where another view should be, I get the expected action so the views are there, just not visible. Only I can't see where I am clicking! I had to upgrade to Xcode 16 to recompile the app and run it in Debug mode. When I do, I get the following: NSBundle file:///System/Library/PrivateFrameworks/MetalTools.framework/ principal class is nil because all fallbacks have failed. Can't find or decode disabled use cases. applicationSupportsSecureRestorableState FWIW - the only view that actually shows up is the last subview added to the main view.
2
1
401
Nov ’24
Tile & Scale an Image
Working on a macOS app. I need to display user-added images as a background to the view, with all of: Tiling (auto repeat in both axes) Scaling (user-configured scale of the image) Offset (user-configured offset) I've been able to achieve scaling and offset with: Image(nsImage: nsImage) .scaleEffect(mapImage.scale) .offset(mapImage.offset) .frame(width: scaledImageSize.width, height: scaledImageSize.height) But when I try to incorporate tiling into that with .resizable(resizingMode: .tile) everything breaks. Is there a way to position the "anchor" of an image, scale it, and tile it in both axes to fill a container view?
1
0
195
Nov ’24
`SwiftUI.FileExportOperation.Error error 0` with `fileExporter` and `NSImage`
You'll have to forgive me, I am still pretty new to Swift, but I'm really struggling to figure out what I'm doing wrong or how I can fix it. I'm working on an app that generates an image from some views and then exports that image, but it always returns this very vague error: The operation couldn’t be completed. (SwiftUI.FileExportOperation.Error error 0.) Here's most of the program: import SwiftUI import UniformTypeIdentifiers struct ContentView: View { @State private var backgroundColor = Color.black @State private var fileExporterIsPresented = false @State private var image: NSImage? @State private var fileExporterErrorAlertIsPresented = false @State private var fileExporterErrorDescription: String? var body: some View { let wallpaper = Rectangle() .foregroundStyle(backgroundColor) .aspectRatio(16 / 9, contentMode: .fit) VStack { wallpaper .clipShape(.rect(cornerRadius: 10)) .overlay { RoundedRectangle(cornerRadius: 10) .strokeBorder(.separator, lineWidth: 5) } ColorPicker("Background Color", selection: $backgroundColor, supportsOpacity: false) Button("Generate Wallpaper") { let renderer = ImageRenderer(content: wallpaper.frame(width: 3840, height: 2160)) image = renderer.nsImage fileExporterIsPresented = true } .fileExporter( isPresented: $fileExporterIsPresented, item: image, contentTypes: [UTType.heic, UTType.png] ) { result in if case .failure(let error) = result { fileExporterErrorDescription = error.localizedDescription fileExporterErrorAlertIsPresented = true } } .alert("File Exporter Failure", isPresented: $fileExporterErrorAlertIsPresented, actions: { Button("OK") {} }, message: { if let fileExporterErrorDescription { Text(fileExporterErrorDescription) } }) .dialogSeverity(.critical) } .padding() } } #Preview { ContentView() }
1
0
256
Nov ’24
NSTextView Contents Disappear When Ruler shown
I have a problem with rulers in an NSTextView. My code has worked fine from about Sierra (10.12), up to Ventura (13), it stopped working in Sonoma and continues to fail in the same way in Sequoia (14 - 15). When I display the ruler, the contents of the text area disappears leaving just a pale grey background. When I make the ruler invisible again the text reappears. No errors are reported (at compile or run time). I have tried adding refreshes of the text view in various places with no result. I have (for Sequoia) used Interface Builder to force the text view to use TextKit 1, also with no success. I’m at a loss as to how to proceed because I’m not getting any diagnostics, simply changed behaviour. My app provides a programming IDE. It includes a program editor that uses line numbering code for an NSTextView from WWDC/Noodlesoft. The line numbers are shown in the ruler which is sometimes visible and sometimes not. When I display the ruler, I also set the main text to not editable but removing this setting does not appear to make any difference. Any suggestions would be very wel PLATFORM AND VERSION macOS, Objective C Development environment: Xcode Version 16.0 (16A242d) [and previously Xcode 15], macOS All releases of Sonoma and Sequoia 15.0.1 (24A348) Run-time configuration: macOS Sequoia 15.0.1 (24A348) The sequence is essentially: [editTextView setEditable:NO]; [self showRulerIn:editTextView visible:YES]; Using: -(void)showRulerIn:(NSTextView*)editorTv visible:(BOOL)vis { NSScrollView *scrollV = [editorTv enclosingScrollView]; NSClipView *clipV = [scrollV contentView]; MBEditorTextView *textView = (MBEditorTextView*)[scrollV documentView]; // The actual text [scrollV setRulersVisible:vis]; // Creates the ruler if necessary … return; } LINE NUMBERING CODE The line number code comes from 2 sources but they are so similar that one must be derived from the other: Apple’s WWDC 2010 code at: https://download.developer.apple.com/videos/wwdc_2010__hd/session_114__advanced_cocoa_text_tips_and_tricks.mov Noodlesoft's code at: https://www.noodlesoft.com/blog/2008/10/05/displaying-line-numbers-with-nstextview/
2
0
302
Nov ’24
Struggling with NSScrollView
I'm still discovering swift and the various frameworks. So I'm now trying to create scrolling composition with a grid - containing images - and an NSStackView at on top. However, I'm running into a problem that might seem stupid, but when I try to wrap my NSCollectionView in another NSView and pointing the scrollView.documentView to, I can't scroll anymore... Even though it works fine when I set the scrollView.documentView to the NSCollectionView directly. Working case: override func viewDidLoad() { super.viewDidLoad() scrollView = NSScrollView(frame: .zero) scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false scrollView.scrollerStyle = .overlay scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) vStack = NSStackView(frame: .zero) vStack.orientation = .vertical vStack.spacing = 12 * 2 vStack.translatesAutoresizingMaskIntoConstraints = false let hStack = NSStackView() hStack.orientation = .horizontal hStack.spacing = 12 hStack.translatesAutoresizingMaskIntoConstraints = false let label1 = NSTextField(labelWithString: "Collection") hStack.addArrangedSubview(label1) let layout = PinterestLayout() layout.delegate = self collectionView = NSCollectionView(frame: .zero) collectionView.collectionViewLayout = layout collectionView.dataSource = self collectionView.delegate = self collectionView .register( ArtCardCell.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell") ) collectionView.backgroundColors = [.BG] collectionView.translatesAutoresizingMaskIntoConstraints = false // vStack.addArrangedSubview(hStack) // vStack.addArrangedSubview(collectionView) scrollView.documentView = collectionView NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), // vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), // vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), // vStack.topAnchor.constraint(equalTo: scrollView.topAnchor), // vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), // vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor), collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), // vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12), // vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12), // vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80) ]) collectionView.postsBoundsChangedNotifications = true NotificationCenter.default.addObserver(self, selector: #selector(didScroll(_:)), name: NSView.boundsDidChangeNotification, object: collectionView.enclosingScrollView?.contentView ) } collectionView height: 3549.0 ScrollView height: 628.0 StackView height: -- Dysfunctional case: override func viewDidLoad() { super.viewDidLoad() scrollView = NSScrollView(frame: .zero) scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false scrollView.scrollerStyle = .overlay scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) vStack = NSStackView(frame: .zero) vStack.orientation = .vertical vStack.spacing = 12 * 2 vStack.translatesAutoresizingMaskIntoConstraints = false let hStack = NSStackView() hStack.orientation = .horizontal hStack.spacing = 12 hStack.translatesAutoresizingMaskIntoConstraints = false let label1 = NSTextField(labelWithString: "Collection") hStack.addArrangedSubview(label1) let layout = PinterestLayout() layout.delegate = self collectionView = NSCollectionView(frame: .zero) collectionView.collectionViewLayout = layout collectionView.dataSource = self collectionView.delegate = self collectionView .register( ArtCardCell.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("ArtCardCell") ) collectionView.backgroundColors = [.BG] collectionView.translatesAutoresizingMaskIntoConstraints = false vStack.addArrangedSubview(hStack) vStack.addArrangedSubview(collectionView) scrollView.documentView = vStack NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), vStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), vStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), vStack.topAnchor.constraint(equalTo: scrollView.topAnchor), vStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), vStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor), collectionView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), vStack.arrangedSubviews[0].leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 12), vStack.arrangedSubviews[0].trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -12), vStack.arrangedSubviews[0].topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 80) ]) } collectionView height: 508.0 ScrollView height: 628.0 StackView height: 628.0
0
0
207
Nov ’24
How can a window be visible but not in the onscreen list?
I'm looking at a case where a handler for NSWindowDidBecomeMain gets the NSWindow* from the notification object and verifies that window.isVisible == YES, window.windowNumber > 0 and window.screen != nil. However, window.windowNumber is missing from the array [NSWindow windowNumbersWithOptions: NSWindowNumberListAllSpaces] and from CGWindowListCopyWindowInfo( kCGWindowListOptionOnScreenOnly, kCGNullWindowID ), how can that be? The window number is in the array returned by CGWindowListCopyWindowInfo( kCGWindowListOptionAll, kCGNullWindowID ). I'm seeing this issue in macOS 15, maybe 14, but not 13.
2
0
312
Nov ’24
Content size of NSWindow returns zero frame after setting view on macOS 15.0 and xCode 16.1
I would like to show a nswindow at a position on screen base on height of the nswindow and its content view. I received zero width and height on macOS 15.0 and xCode 16.1 however they were returned correct width and height on previous macOS version. import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate { private var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { window = NSWindow( contentRect: .zero, styleMask: [.miniaturizable, .closable, .resizable], backing: .buffered, defer: false) window.title = "No Storyboard Window" window.contentView = NSHostingView(rootView: ContentView()) // a swiftui view window.center() let windowFrame = window.frame print("window Frame \(windowFrame)") // print width and height zero here window.makeKeyAndOrderFront(nil) } } struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } I tried window.layoutIfNeeded() after setting contentview but it didn't work How can I get the frame after setting contentview for nswindow on macOS 15.0?
1
0
342
Nov ’24