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

Posts under AppKit tag

184 Posts

Post

Replies

Boosts

Views

Activity

NSScrollView scrolling hitch
When scrolling a basic NSScrollView there seems to be a sudden jump after each flick. Scrolling does not appear smooth and is disorientating. A scroll jump seems to happen directly after letting go of a scroll flick using a trackpad/mouse. Right at that moment the scroll turns into a momentum scroll, slowly decreasing the speed. But the first frame after the gesture the content jumps forward, more than what is expected. Observations: Counterintuitively, scrolling appears to be smoother when disabling NSScrollView.isCompatibleWithResponsiveScrolling. If disabled using a custom NSScrollView subclass there is no large jump anymore. Scrolling also appears to be smoother using a SwiftUI ScrollView. I assume that has the same behaviour as a disabled isCompatibleWithResponsiveScrolling Ironically a WKWebView scrolls much smoother. No sudden jump is observable. It also seems to scroll with faster acceleration, but the individual frames do appear smoother. Why is this better than a native NSScrollView? Elastic scrolling at the bounds of the scroll view also appears much smoother for WKWebViews. When pulling to refresh there is a jump for NSScrollView/SwiftUI, but not for WKWebView. When using an NSScrollView with isCompatibleWithResponsiveScrolling disabled, scrolling appears just as smooth as WKWebView on macOS 13 Ventura and below. On macOS 14 Sonoma scrolling behaviour is suddenly different. Please see a sample project with 4 different scroll views side by side: https://github.com/floorish/ScrollTest Screen recordings show the sudden jumps when scrolling and when elastic scrolling. Tested on Intel & Arm Macs, macOS 11 Big Sur through 15 Sequoia, built with Xcode 16. Should isCompatibleWithResponsiveScrolling be disabled on Sonoma+? Are there any drawbacks? There is also no overdraw anymore since Monterey, as described in https://developer.apple.com/library/archive/releasenotes/AppKit/RN-AppKitOlderNotes/#10_9Scrolling Even with responsive scrolling disabled, why is WKWebView scrolling much smoother than NSScrollView?
Topic: UI Frameworks SubTopic: AppKit Tags:
5
1
570
3d
Why does AppStore.requestReview(in:) require NSViewController Parameter?
Looking to update one of my apps that uses SKStoreReviewController +requestReview (deprecated) to AppStore.requestReview(in:) umm...I have a few of questions... Why is an NSViewController parameter required? It's really not so uncommon for an AppKit app to just use NSWindowController with a window that does not use NSViewController... It should be possible to present the review request in a standalone alert (attached to a window is preferred IMO but it still should be possible to ask in separate window). 3)...why Swift..(err nevermind) Ideally: AppStore requestReview should take a NSWindow parameter but that parameter should be optional. If nil the request should be presented in a standalone window (like an alert). If non nil..present as a sheet on the window. Why a view controller? Maybe I'm missing something.
2
0
68
3d
Grammar checking is never requested
I have prepared a NSSpellServer spelling and grammar checker for Slovenian proofing in macOS. My proofing service gets used when I explicitly set keyboard spelling language to "Slovenian (Besana)" (my proofing service). However, no matter how I set the Check Grammar With Spelling option or Check Grammar checkbox in the TextEdit.app or Mail.app, my proofing service does not get any request for grammar checking. I am supporting checkString call for Unified checking and checkingTypes never contains NSTextCheckingTypeGrammar flag. When using legacy API before Unified checking support, the checkGrammarInString is never called either. If I do the grammar regardless the checkingTypes parameter, the app shows grammar mistakes correctly. But that is bad UX. Need to follow user demand for with grammar or without grammar. I don't know what am I doing wrong? On my home iMac v11 it actually works. No idea what I did there to make it work. Just worked. On my working Mac Mini v13 it won't check grammar. On another MacBook Pro v15, it won't check grammar either. Apps do check spelling with my proofing service. But not grammar. Same apps do grammar checking with stock AppleSpelling.service just fine. I have checked my Info.plist, using Hardened Runtime, have empty Entitlements, to no avail. Was there some new grammar API introduced after macOS v11 Big Sur, I should implement? Is there some specific Entitlement, signature, notarization I should perform to get going? Some documentation I am missing?
2
0
86
3d
ProgressView Tint doesn't work on macOS
I seem to be unable to affect the color of a linear ProgressView() on macOS and need to know if this is a feature or a bug. I have the following: ProgressView(value: someProgress).tint(.green) This works fine in iOS, the linear ProgressView changes to the desired color. On macOS the ProgressView stays the color of the system accent. .progressViewStyle(LinearProgressViewStyle(tint: .blue)) Is available, but depreciated, or being depreciated. I have also tried: .tint(.red) .accentColor(.green) While I can understand the platform specific differences, the context that I'm using really would benefit from keeping the UI elements colored consistent with the app, rather than the OS. Also I can do it in iOS, why not macOS? Both dev and test machines are running latest updates (Xcode 26.0.1/macOS 26.0.1 and iOS 26.0.1/macOS26.0.1)
3
0
100
4d
Resizing text to fit available space
My app displays some text that should appear the same regardless of the container view or window size, i.e. it should grow and shrink with the container view or window. On iOS there is UILabel.adjustsFontSizeToFitWidth but I couldn't find any equivalent API on macOS. On the internet some people suggest to iteratively set a smaller font size until the text fits the available space, but I thought there must be a more efficient solution. How does UILabel.adjustsFontSizeToFitWidth do it? My expectation was that setting a font's size to a fraction of the window width or height would do the trick, but when resizing the window I can see a slightly different portion of it. class ViewController: NSViewController { override func loadView() { view = MyView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) NSLayoutConstraint.activate([view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 3), view.heightAnchor.constraint(greaterThanOrEqualToConstant: 100)]) } } class MyView: NSView { let textField = NSTextField(labelWithString: String(repeating: "a b c d e f g h i j k l m n o p q r s t u v w x y z ", count: 2)) override init(frame frameRect: NSRect) { super.init(frame: frameRect) textField.translatesAutoresizingMaskIntoConstraints = false textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) addSubview(textField) NSLayoutConstraint.activate([textField.topAnchor.constraint(equalTo: topAnchor), textField.leadingAnchor.constraint(equalTo: leadingAnchor), textField.trailingAnchor.constraint(equalTo: trailingAnchor)]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func resize(withOldSuperviewSize oldSize: NSSize) { // textField.font = .systemFont(ofSize: frame.width * 0.05) textField.font = .systemFont(ofSize: frame.height * 0.1) } }
Topic: UI Frameworks SubTopic: AppKit Tags:
11
0
248
4d
NSDocument doesn't autosave last changes
I had noticed an unsettling behaviour about NSDocument some years ago and created FB7392851, but the feedback didn't go forward, so I just updated it and hopefully here or there someone can explain what's going on. When running a simple document-based app with a text view, what I type before closing the app may be discarded without notice. To reproduce it, you can use the code below, then: Type "asdf" in the text view. Wait until the Xcode console logs "saving". You can trigger it by switching to another app and back again. Type something else in the text view, such as "asdf" on a new line. Quit the app. Relaunch the app. The second line has been discarded. Am I doing something wrong or is this a bug? Is there a workaround? class ViewController: NSViewController { @IBOutlet var textView: NSTextView! } class Document: NSDocument { private(set) var text = "" override class var autosavesInPlace: Bool { return true } override func makeWindowControllers() { let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil) let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as! NSWindowController (windowController.contentViewController as? ViewController)?.textView.string = text self.addWindowController(windowController) } override func data(ofType typeName: String) throws -> Data { Swift.print("saving") text = (windowControllers.first?.contentViewController as? ViewController)?.textView.string ?? "" return Data(text.utf8) } override func read(from data: Data, ofType typeName: String) throws { text = String(decoding: data, as: UTF8.self) (windowControllers.first?.contentViewController as? ViewController)?.textView.string = text } }
Topic: UI Frameworks SubTopic: AppKit Tags:
17
0
393
4d
Window title bar in macOS 26 is drawn even if titlebarAppearsTransparent = true
macOS 26 sometimes draws the title bar background even when setting NSWindow.titlebarAppearsTransparent = true and I don't understand the logic behind it, or how I can turn this off. I'm trying to do something similar to Xcode's "Welcome to Xcode" window which has a left view and a right table view. In my simplified example, the window contains a label and a text view. This used to work in macOS 15, but in macOS 26 the text view is partially covered by the title bar: As soon as I remove the line scrollView.hasVerticalScroller = true, the title bar isn't drawn anymore: The title bar also isn't drawn when removing the view on the left of the text view: I created FB20341654. This may be related to this other issue: NSWindow.titlebarAppearsTransparent only works after collapsing and expanding sidebar @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { let window = NSWindow(contentViewController: ViewController()) window.titlebarAppearsTransparent = true window.titleVisibility = .hidden window.styleMask = [.titled, .closable, .fullSizeContentView] window.makeKeyAndOrderFront(nil) } } class ViewController: NSViewController { override func loadView() { view = NSView(frame: CGRect(x: 0, y: 0, width: 400, height: 200)) let scrollView = NSScrollView() scrollView.hasVerticalScroller = true // commenting this line out solves the issue scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.automaticallyAdjustsContentInsets = false let documentView = NSTextView() documentView.string = (0..<10).map({ "\($0)" }).joined(separator: "\n") scrollView.documentView = documentView let stack = NSStackView(views: [ NSTextField(labelWithString: "asdfasdfasdfasdf"), // commenting this line out also solves the issue scrollView ]) stack.orientation = .horizontal view.addSubview(stack) NSLayoutConstraint.activate([stack.topAnchor.constraint(equalTo: view.topAnchor), stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), stack.bottomAnchor.constraint(equalTo: view.bottomAnchor)]) } }
Topic: UI Frameworks SubTopic: AppKit Tags:
2
0
141
6d
NSHostingSceneRepresentation doesn't show Window(_:id:) and UtilityWindow(_:id:) with .openWIndow(id:)
NSHostingSceneRepresentation, introduced in macOS 26, allows calling SwiftUI’s windows and other elements set in a Scene from AppKit. However, while Settings and WindowGroup set in the Scene can be invoked as expected using environment.openSettings() and environment.openWindow(id:) respectively, calling Window or WindowUtility doesn’t work. That is, the app just fails to open the desired window with the provided ID, and no error message or other feedback/crash/freeze appears. I expect that executing the openUtilityWindow(_:)action in the following code will display the UtilityWindow set in the scene. However, the window does not actually open. @main final class AppDelegate: NSObject, NSApplicationDelegate { private let scene = NSHostingSceneRepresentation { UtilityWindow("Utility Window", id: "UtilityWindow") { Text("Utility Window") .scenePadding() } } func applicationWillFinishLaunching(_ notification: Notification) { NSApp.addSceneRepresentation(self.scene) } @IBAction func openUtilityWindow(_ sender: Any?) { self.scene.environment.openWindow(id: "UtilityWindow") } } Is there something wrong with my implementation and expectation? Or is this a bug in NSHostingSceneRepresentation? Just in case, I’ve already filed this issue withFeedback Assistant: FB20310722 This feedback also includes a sample project reproducing this issue.
0
0
37
1w
Did GCD change in macOS 26
Some users of my Mac app are complaining of redrawing delays. Based on what I see in logs, my GCD timer event handlers are not being run in a timely manner although the runloop is still pumping events: sometimes 500ms pass before a 15ms timer runs. During this time, many keypresses are routed through -[NSApplication sendEvent:], which is how I know it's not locked up in synchronous code. This issue has not been reported in older versions of macOS. I start the timer like this: _gcdUpdateTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); dispatch_source_set_timer(_gcdUpdateTimer, dispatch_time(DISPATCH_TIME_NOW, period * NSEC_PER_SEC), period * NSEC_PER_SEC, 0.0005 * NSEC_PER_SEC); dispatch_source_set_event_handler(_gcdUpdateTimer, ^{ …redraw… });
1
0
63
1w
Why isn't Liquid Glass effect applied when using pyobjc?
I can compile this #import <Cocoa/Cocoa.h> @interface AppDelegate : NSObject <NSApplicationDelegate> @property (strong) NSWindow *window; @property (strong) NSSlider *slider; @end @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)notification { // Window size NSRect frame = NSMakeRect(0, 0, 400, 300); NSUInteger style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable; self.window = [[NSWindow alloc] initWithContentRect:frame styleMask:style backing:NSBackingStoreBuffered defer:NO]; [self.window setTitle:@"Centered Slider Example"]; [self.window makeKeyAndOrderFront:nil]; // Slider size CGFloat sliderWidth = 200; CGFloat sliderHeight = 32; CGFloat windowWidth = self.window.frame.size.width; CGFloat windowHeight = self.window.frame.size.height; CGFloat sliderX = (windowWidth - sliderWidth) / 2; CGFloat sliderY = (windowHeight - sliderHeight) / 2; self.slider = [[NSSlider alloc] initWithFrame:NSMakeRect(sliderX, sliderY, sliderWidth, sliderHeight)]; [self.slider setMinValue:0]; [self.slider setMaxValue:100]; [self.slider setDoubleValue:50]; [self.window.contentView addSubview:self.slider]; } @end int main(int argc, const char * argv[]) { @autoreleasepool { NSApplication *app = [NSApplication sharedApplication]; AppDelegate *delegate = [[AppDelegate alloc] init]; [app setDelegate:delegate]; [app run]; } return 0; } with (base) johnzhou@Johns-MacBook-Pro liquidglasstest % clang -framework Foundation -framework AppKit testobjc.m and get this neat liquid glass effect: https://github.com/user-attachments/assets/4199493b-6011-4ad0-9c9f-25db8585e547 However if I use pyobjc to make an equivalent import sys from Cocoa import ( NSApplication, NSApp, NSWindow, NSSlider, NSMakeRect, NSWindowStyleMaskTitled, NSWindowStyleMaskClosable, NSWindowStyleMaskResizable, NSBackingStoreBuffered, NSObject ) class AppDelegate(NSObject): def applicationDidFinishLaunching_(self, notification): # Create the main window window_size = NSMakeRect(0, 0, 400, 300) style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable self.window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_( window_size, style, NSBackingStoreBuffered, False ) self.window.setTitle_("Centered Slider Example") self.window.makeKeyAndOrderFront_(None) # Slider size and positioning slider_width = 200 slider_height = 32 window_width = self.window.frame().size.width window_height = self.window.frame().size.height slider_x = (window_width - slider_width) / 2 slider_y = (window_height - slider_height) / 2 self.slider = NSSlider.alloc().initWithFrame_(NSMakeRect(slider_x, slider_y, slider_width, slider_height)) self.slider.setMinValue_(0) self.slider.setMaxValue_(100) self.slider.setDoubleValue_(50) self.window.contentView().addSubview_(self.slider) if __name__ == "__main__": app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() app.setDelegate_(delegate) app.run() I get a result shown at https://github.com/user-attachments/assets/7da022bc-122b-491d-9e08-030dcb9337c3 which does not have the new liquid glass effect. Why is this? Is this perhaps related to the requirement that you must compile on latest Xcode as indicated in the docs? Why, is the compiler doing some magic?
3
0
231
1w
What is SwiftUI API equivalent to NSSplitViewItemAccessoryViewController in macOS?
On macOS Tahoe 26, NSSplitViewController introduced the NSSplitViewItemAccessoryViewController and related-APIs in NSSplitViewController, such as addBottomAlignedAccessoryViewController(_:). Those APIs allow you to place accessory views at the top and bottom of a split view with a nice edge effect. I understand how to use them with AppKit. However, I’m not sure how to achieve the same functionality with SwiftUI.
1
0
61
1w
SwiftUI TextField selects all text when it gains focus — how to move caret to the end like in AppKit?
I’m running into an issue with TextField focus behavior in SwiftUI. By default, when I set focus to a TextField programmatically (using @FocusState), SwiftUI behaves like AppKit — the entire contents of the text field are selected. This is causing problems for my use case, because I want the caret placed at the end of the text without selecting everything. How I solved this in AppKit In AppKit, I worked around this by subclassing NSTextField and overriding becomeFirstResponder to adjust the editor’s selection: override func becomeFirstResponder() -> Bool { let responderStatus = super.becomeFirstResponder() // Ensure caret is placed at the end, no text selected if let editor = self.currentEditor() { let selectedRange = editor.selectedRange editor.selectedRange = NSRange(location: selectedRange.length, length: 0) } return responderStatus } This successfully prevented AppKit from auto-selecting the entire string when focus changed. The problem in SwiftUI Now I see the same auto-select behavior in SwiftUI when I toggle focus with @FocusState. But unlike AppKit, SwiftUI doesn’t expose the underlying NSTextView or UITextField APIs, so I can’t directly adjust the selection or caret position. Questions: Is there a way in SwiftUI to control the caret/selection behavior when a TextField becomes focused? Is there a built-in modifier or @FocusState trick I’m missing? Has anyone found a reliable SwiftUI-idiomatic approach to ensure the caret is placed at the end of the text instead of selecting all text? update: adding my swiftUI code below: struct TextFieldUI: View { @ObservedObject var pModel:TextFieldModel @FocusState private var pIsFocusedState: Bool var body: some View { VStack(spacing: 20) { TextField(pModel.placeholder, text: $pModel.text) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() .focused($pIsFocusedState) .onChange(of: pModel.isFocused) { old, newValue in pIsFocusedState = newValue } .onChange(of: pIsFocusedState) { old, newValue in pModel.isFocused = newValue } .onAppear { pIsFocusedState = pModel.isFocused } Toggle("Secure Mode", isOn: $pModel.isSecure) .padding() } .padding() } }
0
0
58
1w
Icon for some menu items cannot be removed on macOS 26
create a sample XCode project using Objective-C and stroybook (xib) using latest XCode beta open MainMenu.xib, and select Main Menu → File → Print... remove the image like below 4. build it 5. run it on macOS 26 beta 7 6. The menu item "print.." still have "Image" Is there any way to remove image for one menu item. I have also tried NSMenuItem.image = nil, but still not work. The issue I met on my own app is that I cannot remove icons for "Zoom In", "Zoom Out" and many other menu items, which makes the menu items not aligned properly.
1
0
145
1w
NSRulerView's background color and transparency (macOS 26)
When I compiled my legacy project with Tahoe's macOS 26 SDK, NSRulerViews are showing a very different design: Under prior macOS versions the horizontal and verrical ruler's background were blurring the content view, which was extending under the rulers, showing through their transparency. With Tahoe the horizontal ruler is always reflecting the scrollview's background color, showing the blurred content view beneath. And the vertical ruler is always completely transparent (without any blurring), showing the content together with the ruler's markers and ticks. It's difficult to describe, I'll try to replicate this behavior with a minimal test project, and probably file a bug report / enhancement request. But before I take next steps, can anyone confirm this observation? Maybe it is an intentional design decision by Apple?
1
0
85
1w
Bug or Feature: Changes to Window Reopen Behavior in macOS 26
Since macOS 26 Beta 1, I notice that the window reopening behavior had changed. Say there are two desktops (spaces), one might: open an app window in desktop 1 close that window switch to desktop 2 reopen the app window (by click on dock tile, spotlight search...) Prior to macOS 26, that window will always reopen in current desktop. This is IMO the right behavior because these windows are most likely transient (message app, chat app, utilities app or note app). In macOS 26, however, will switch to desktop 1 (where the window is closed) and reopen the window in desktop 1. This is weird to me because: Window is "closed", hence it should not be attached to desktop 1 anymore, unlike minimize. Switching desktop interrupts user's current workflow. It's annoying to switch back specially when there're many desktops. This behavior is inconsistent. Some reopen in current desktop, some reopen in previous desktop. Apps like Music, Notes and Calendar reopened in previous desktop, while Mail, Messages, and Freeform reopened in current desktop. I did a little bit of experiment, and find out that apps that reopened in current desktop are most likely because they take an extra step to release the window when it's closed. I believe this is a bug, so I fire a feedback (FB18016497) back in beta 1. But I did not get any response or similar report from others, to a point that I kinda wonder if this is intended. I can easily force my app to reopen in current desktop by nullifying my window controller in windowWillClose, but this behavior essentially change how one can use the Spaces feature that I think I should bring this up to the community and see what other developers or engineers thinks about it.
Topic: UI Frameworks SubTopic: AppKit Tags:
3
0
160
2w
Liquid Glass icons appear differently in Dock
I just played around on macOS with the new icons created by Icon Composer, and I noticed that the Dock displays programmatically set icons differently. Try this: Make sure you have the Mail app in your Dock. Set the icon appearance to "Tinted/Light" and set a dark (black) background for the Desktop. Run this code: let image = NSWorkspace.shared.icon(forFile: "/System/Applications/Mail.app") if image.isValid { NSApp.applicationIconImage = image } You'll get something like this: When the icon appearance is set to "Default" or "Dark," everything works as expected, and the "Clear/Dark" and "Tinted/Dark" modes seem to work as well. It seems like the Dock uses a special blend mode depending on the selected background, but this does not seem to be the case if the icon is set programmatically. I filed feedback FB20291186.
0
1
609
2w
I need to access information about the apps installed in my system
How do I get the FileManager in SwiftUI to read information about the apps in the Applications folder. Lots of apps do it, Alfred, Raycast. It's not something that is unheard of, and yet I cannot for the life of me, using every kind of guide on the internet figure out how to achieve this. Please somebody help, this is legitimately affecting my mental health.
1
0
145
2w
Default document-based app menu items missing icons
In a new document-based macOS app project created in Xcode, some of the default system-provided menu commands appear without their standard icons in the menu bar. Steps to Reproduce: 1. In Xcode, create a new macOS “Document App” project (using Swift/SwiftUI or AppKit template). 2. Build and run the project. 3. Open the app’s main menu bar and examine the default items such as New Document, Open…, Save, Duplicate, etc. Expected Results: System-provided menu items (e.g. Open…, Save, Duplicate) should display their standard SF Symbol–based icons automatically, as they do in TextEdit and other system apps. Actual Results: Some of these menu items display only text, with no icon namely: Services Open Recent Revert To Share This happens even though the items are the system-managed defaults generated by the document-based app template. Notes: • No code modifications were made — this occurs in a fresh, unedited template project. • Behavior seen on macOS 26.0 (25A354). • Xcode Version 26.0 (17A324) used.
1
0
131
2w
NSWindow.titlebarAppearsTransparent only works after collapsing and expanding sidebar
I'm using the simplified code below to create a window with 4 split view items, some of them collapsed. I would expect the title bar to be transparent since I'm using window.titlebarAppearsTransparent = true, but it seems that this particular view configuration causes the title bar to be visible until I collapse and expand the sidebar again. Removing any of the split view items, uncollapsing any of them, or changing the view of any of the view controllers, causes the title bar to be consistently visible or hidden, although I don't understand the logic, since I'm telling the window that it should be transparent. When launching the app in light mode, it's more difficult to notice the issue since the title bar background is equal to the content background and only the separator is visible (even though the code sets window.titlebarSeparatorStyle = .none): After collapsing and expanding the sidebar, the separator is gone: In dark mode the title bar is more visible: After collapsing and expanding the sidebar, the title bar background and separator are gone: I created FB20306872. @main class AppDelegate: NSObject, NSApplicationDelegate, NSToolbarDelegate { var splitViewController: NSSplitViewController! func applicationDidFinishLaunching(_ aNotification: Notification) { let splitViewItem1 = NSSplitViewItem(sidebarWithViewController: ViewController1()) let splitViewItem2 = NSSplitViewItem(viewController: ViewController2()) let splitViewItem3 = NSSplitViewItem(viewController: NSViewController()) splitViewItem3.isCollapsed = true let splitViewItem4 = NSSplitViewItem(viewController: NSViewController()) splitViewItem4.isCollapsed = true splitViewController = NSSplitViewController() splitViewController.splitViewItems = [splitViewItem1, splitViewItem2, splitViewItem3, splitViewItem4] let window = NSWindow(contentViewController: splitViewController) window.styleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView] window.titlebarAppearsTransparent = true let toolbar = NSToolbar(identifier: "") toolbar.delegate = self toolbar.displayMode = .iconOnly window.toolbar = toolbar window.titlebarSeparatorStyle = .none window.makeKeyAndOrderFront(nil) } func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [.space, .flexibleSpace, .sidebarTrackingSeparator, .init("item")] } func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [.init("item"), .sidebarTrackingSeparator] } func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { switch itemIdentifier.rawValue { case "item": let item = NSToolbarItem(itemIdentifier: itemIdentifier) item.image = NSImage(systemSymbolName: "sidebar.leading", accessibilityDescription: nil) item.action = #selector(toggleSidebar(_:)) item.target = self return item default: return nil } } @objc func toggleSidebar(_ sender: Any?) { splitViewController.splitViewItems[0].animator().isCollapsed = !splitViewController.splitViewItems[0].isCollapsed } } class ViewController1: NSViewController { override func loadView() { view = NSView(frame: CGRect(x: 0, y: 0, width: 300, height: 200)) } } class ViewController2: NSViewController { override func loadView() { let textView = NSTextView() let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 400, height: 200)) scrollView.hasVerticalScroller = true scrollView.documentView = textView view = scrollView } }
Topic: UI Frameworks SubTopic: AppKit Tags:
0
0
51
2w