I’ve finally changed my main development platform to macOS 14 Sonoma and almost immediately have I encountered something I consider being a bug. I searched for similar issues, but nowhere have I found any relevant information or help.
The issue is rather funny; if you have a subview and, for whatever reason, it finds itself outside of its superview’s bounds, it remains visible, instead of being hidden. It’s like you have a window on your room wall, but still the interior of your room is visible outside of window’s borders :-)
Here’s a simple Xcode project that explains what I’m talking about:
https://zigz.ag/temp/SubviewBug/UnhiddenXcodeProject.zip
Unpack and build this project, run the test application and see it yourself.
However, there are some differences, regarding the Xcode/SDK version used to build the application and the macOS version it runs on. The project format is “Xcode 13.0” and MACOSX_DEPLOYMENT_TARGET = 13.0. Here you can find application bundle, build with Xcode 14:
https://zigz.ag/temp/SubviewBug/UnhiddenXcode14Build.zip
The relevant build parameters, as found in application's Info.plist are:
BuildMachineOSBuild: 22G605
DTPlatformVersion: 13.3
DTSDKBuild: 22E245
DTXcode: 1431
DTXcodeBuild: 14E300c
If you run it on both Ventura and Sonoma, you’ll see ti behaves as expected. However, here you can find application bundle, build with Xcode 15:
https://zigz.ag/temp/SubviewBug/UnhiddenXcode15Build.zip
The relevant build parameters, as found in application's Info.plist are:
BuildMachineOSBuild: 23D56
DTPlatformVersion: 14.2
DTSDKBuild: 23C53
DTXcode: 1520
DTXcodeBuild: 15C500b
Now, if you run this build on Ventura, you’ll see it behaves fine. Running it on Sonoma however, shows the behaviour I’m trying to explain; the ratio button titled “Two” remains visible, even though its superview shrinks and it goes out of its superview’s bounds. So, the issue is present only on Sonoma, if build with Xcode 15.
The difference is visible even inside Interface Builder. Here is a short video of shrinking a superview in IB of Xcode 14, note how the “Two” radio button becomes invisible, as it goes outside of its superview’s bounds:
https://zigz.ag/temp/SubviewBug/InterfaceBuilderXcode14.mov
Here is the video of shrinking the same superview in IB of Xcode 15, the “Two” radio button remains visible regardless of its superview’s bounds:
https://zigz.ag/temp/SubviewBug/InterfaceBuilderXcode15.mov
Is this a bug? Or did I miss something in macOS 14 Sonoma SDK release notes, which would indicate from now on this is expected behaviour (highly unlikely)?
-- Dragan
AppKit
RSS for tagConstruct and manage a graphical, event-driven user interface for your macOS app using AppKit.
Post
Replies
Boosts
Views
Activity
I have a custom NSView embedded in a NSScrollView.
[NSView drawRect:] is called once, when the window is created and displayed, and the rendering is exactly how it should be.
Then I resize (shrink) the window, which does not make [NSView drawRect:] being called again, as no new part of my view needs to be drawn; however, the window's content is flushed again on screen, and the rendering is now different.
How could this be possible? I am logging a message in my [NSView drawRect:] implementation, so I am absolutely certain that it is called only once in this scenario. Is it possible that a single drawing instruction ([NSBezierPath stroke], in this case) called only once actually produces two different rendered images, in two different drawing buffers, and that the buffer flushed to the screen can change depending on the size of the window??
Now, what is different in the rendering? Two things: antialiasing is performed differently (the line width is 0.25 pixel), correctly in the first case, and not very smoothly in the second case. I also changed [NSBezierPath setFlatness:], and this flatness is taken in account in the first case, and unchanged (default flatness) in the second case.
When I continue to resize the window, enlarging then shrinking it, drawRect: is called when I enlarge it, and depending on the window size, sometimes I get the "correct" rendering, and sometimes the "wrong" one (for the whole view; it is not limited to the newly revealed area).
I have a built-in display set to "more space", and an external non-retina monitor; with "desktop & dock" settings set to "displays have different Spaces", in case this has any impact on the situation.
This might sound strange and but I'd really like to get this resolved.
I first though this was the fault of a macos application that I developed. But later I noticed that it is practically applies to every application on the macbook I've got.
If I press "Help" in the menu-bar, in any app on my mac. That app crashes.
In some apps, it crashes directly, in some, it show a corrupt list first, then crashes. This is how it looks in Safari for example (1 second after pressing "Help"):
Here's the stacktrace for Safari:
0 libobjc.A.dylib 0x181319c20 objc_msgSend + 32
1 Shortcut 0x1bd7aca5c -[SCTSearchManager hasNoResults] + 56
2 Shortcut 0x1bd7aea78 -[SCTSearchManager selectRowAfterTargetingItem:withMenu:] + 36
3 Shortcut 0x1bd7abdc4 SCTHelpMenuHandler + 508
4 HIToolbox 0x18afbb3a4 DispatchEventToHandlers(EventTargetRec*, OpaqueEventRef*, HandlerCallRec*) + 1092
5 HIToolbox 0x18afba828 SendEventToEventTargetInternal(OpaqueEventRef*, OpaqueEventTargetRef*, HandlerCallRec*) + 356
6 HIToolbox 0x18afba6b8 SendEventToEventTargetWithOptions + 44
7 HIToolbox 0x18b188878 SendItemEvent(MenuSelectData*, unsigned int, MenuData*, unsigned short) + 308
8 HIToolbox 0x18b050f10 UpdateMenuViewFocus(MenuSelectData*, MenuData*, short, short) + 568
9 HIToolbox 0x18b04be28 ViewFocusHandler(OpaqueEventHandlerCallRef*, OpaqueEventRef*, void*) + 520
10 HIToolbox 0x18afbb3a4 DispatchEventToHandlers(EventTargetRec*, OpaqueEventRef*, HandlerCallRec*) + 1092
11 HIToolbox 0x18afba828 SendEventToEventTargetInternal(OpaqueEventRef*, OpaqueEventTargetRef*, HandlerCallRec*) + 356
12 HIToolbox 0x18afba6b8 SendEventToEventTargetWithOptions + 44
13 HIToolbox 0x18b02f528 HIView::SendSetFocusPart(short, unsigned char, unsigned char, short*) + 248
14 HIToolbox 0x18b02f394 HIView::SetFocusPartInternal(short, unsigned char, unsigned char, short*, short, unsigned char, unsigned char) + 116
15 HIToolbox 0x18b02f14c HIView::SetFocusPart(short, unsigned char, unsigned char, unsigned int, FocusData*) + 240
16 HIToolbox 0x18b02ef90 HIViewSetFocus + 168
17 HIToolbox 0x18b05049c ChooseItem(MenuSelectData*, Rect const*) + 220
18 HIToolbox 0x18b1876e4 TrackMenuCommon(MenuSelectData&, unsigned char*, SelectionData*, MenuResult*, MenuResult*) + 800
19 HIToolbox 0x18b052c0c MenuSelectCore(MenuData*, Point, double, unsigned int, OpaqueMenuRef**, unsigned short*) + 348
20 HIToolbox 0x18b052a00 _HandleMenuSelection2 + 416
21 AppKit 0x184b09918 _NSHandleCarbonMenuEvent + 256
22 AppKit 0x184b0973c _DPSEventHandledByCarbon + 60
23 AppKit 0x1849b7104 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 2232
24 Safari 0x1ac42a218 -[BrowserApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 228
25 AppKit 0x1849aaf7c -[NSApplication run] + 464
26 AppKit 0x1849823cc NSApplicationMain + 880
27 Safari 0x1ac791e24 SafariMain + 408
28 dyld 0x18135bf28 start + 2236
This is a problem that only exists on MacOS 13 (Ventura) and MacOS 14 (Sonoma). On all earlier versions of MacOS, the existing code works well, and has for many years.
I am working on an long-running Objective-C MacOS app (non-sandboxed) that uses WKWebView to display a static web page within a "pane" of a larger NSView. By "pane", I mean the WKWebView might be the only view within the encompassing NSView (thereby occupying all of its space), or it might occupy only one rectangle within it, if the NSView is divided into arbitrary rectangles.
(Whether or not the WKWebView takes up the entire surrounding rectangle, or just a section of it, seems irrelevant.)
The WKWebView is created offscreen at startup time, and later may become visible under user control. I don't need the displayed web page to permit any interactivity with the user other than scrolling, and I disable Javascript on the page using the WKWebViewConfiguration - which appears to work as intended.
I therefore have no need for NSTrackingArea either, and am not using it. It does appear that the WKWebView has one NSTrackingArea by default, but it's not mine. I can remove it programmatically, but that does not appear to make any difference.
When the WKWebView is visible, the app will instantly crash as soon as the cursor enters its rectangle.
The stack trace shows the error:
[_NSTrackingAreaCGViewHelper cursorAreas]: unrecognized selector sent to instance
The problem here is that the _NSTrackingAreaCGViewHelper method appears to be something within an Apple internal framework - I can't find discussion of it anywhere on the Internet, or in Apple's developer docs. Same for the selector "cursorAreas" - I can't find any information about it at all.
So this is starting to feel like a bug somewhere in Apple's internal framework. I can't understand why it's crashing with a message related to NSTrackingArea (or similar objects), when I'm not using tracking at all, but the "unrecognized selector" error is even more disturbing - I'm not calling the method, and certainly can't control the selector. I can't be sure, but this feels like Apple's error.
I'd like to know if there might be a way for me to configure WKWebView to not use tracking at all, thereby eliminating the issue entirely, but I can't find a way to do that other than removing the NSTrackingAreas from the WKWebView, but that's not helping either.
Can anyone (especially from Apple) offer any guidance? If it's an Apple bug, I would love to know how to work around it - it's a show-stopper for this app.
Thanks in advance...
Hi folks,
In my macOS app I’m using NSColorPanel to present color picking options to the user. Therefore I’m attaching various custom NSColorLists before showing the color panel. The panel is always presented with the „Apple“ color list active, and I found no method to select a different color list. In my app I could determine the most relevant color list and would like to preselect it instead of relying on a manual selection by the user.
Is there any option to control the selected / active NSColorList of an NSColorPanel?
Additionally - but that more a minor topic and probably a candidate for a bug report: Since some major macOS versions (maybe starting with macOS 13 „Ventura“?) the order of NSColorLists in the default NSColorPanel is random. In the past color palettes were listed in reverse order of their attachments via „attachColorList:“.
Is there any way to control the order color palettes are listed by an NSColorPanel
I just spent one of my TSIs for this question - as my Apple developer membership is renewed shortly - but maybe this community as some smart tip to share...
Appreciate any help, Mattes
I can't get CoreImage to render an HDR image file with correct colors to a CAMetalLayer on macOS 14. I'm comparing the result with NSImageView and the SupportingHDRImagesInYourApp 'HDRDemo23' sample code, which use CVPixelBuffer. With CAMetalLayer, the images are displayed as HDR (definitely more highlights), but they're darker with some kind saturation increase & color shift.
Files I've tested include the sample ISO HDR files in the SupportingHDRImagesInYourApp sample code. Methods I've tried to render to CAMetalLayer include:
Modifying the GeneratingAnAnimationWithACoreImageRenderDestination sample code's ContentView so it uses HDRDemo23/example-ISO-HDR-images/image_01.heic, loaded using CIImage(contentsOf:)
Creating a test AppKit app that uses MTKView and CIRenderDestination the same way. I have NSImageView and the MTKView in the same window for comparison.
Using CIRAWFilter > CIRenderDestination > IOSurface > MTKView/CAMetalLayer
All these methods produce the image with the exact same appearance; a dark HDR image with some saturation/color shift.
The only clue I've found is that when using the Metal Debugger on the test AppKit app, the CAMetalLayer's 'Present' shows the 'input' thumbnail is HDR without the color shift, but the 'output' thumbnail looks like what I actually see. I tried changing the color profile on the layer to various things but nothing looked more correct.
I've tried this on two Macs, an M1 Mac Studio with an LG display, and a MacBook Air M2. The MacBook Air shows the same color shift, but since it has less dynamic range overall there isn't as much difference between NSImageView and MTKView.
Is it possible that I bypass tableView.makeView so that I can create a NSTableCellView on the fly (based on some logics)?
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if NSTableColumn.identifier.rawValue == "labelColumn" {
let myCellView = NSTableCellView()
myCellView.textField.strinValue = "label text"
return myCellView
} else {
let complexView = loadFromNib() // of NSTableCellView
// populate complexView
return complexView
}
}
Hi all,
I've been playing around with making a screen saver using ScreenSaver.framework and having issues with (what appears to be) macOS caching the previous version of the screensaver until I reboot.
I have written a screen saver that works, however if I make some changes to the code, re-archive and reinstall the newly compiled screen saver still presents the old screen saver. I've tried incrementing the build number to no avail.
Does anyone have a solution to this?
My workflow :-
Uninstall and delete all instances of my screen saver.
Reboot
Open Xcode, compile, re-archive my screen saver.
Double-click the archived screen-saver, click to install for this user.
Test screensaver -- success!
Now,
Delete the screensaver by right-click on screensaver in System Settings, "Delete "
Make changes to my code, rearchive.
Double-click the archived screen-saver, click to install for this user.
Test screensaver -- fail! Still shows the old version of the screensaver.
Reboot machine
Test screensaver -- success! Screensaver now shows the changes I made.
Many thanks all.
I've created a custom NSCollectionView layout that is vertical in design and it supports dragging and dropping. However, the drawn drop indicator only is a vertical line in the middle of the inter gap or drop zones specified. Ideally, I'd like for this line to be horizontal, extending the width of the frame rather than the vertical and extending the height. Basically, I am trying to replicate the drop indicator that's used in NSTableView or NSOutlineView.
Is there any way to accomplish this?
I have a view (custom subclass of NSView) that overrides mouseDown: and mouseUp:. If I double-click the view, I expect to see a sequence of events:
mouseDown with clickCount == 1
mouseUp with clickCount == 1
mouseDown with clickCount == 2
mouseUp with clickCount == 2
Usually, that's what happens. But occasionally, the second or both mouse up events don't arrive. That's a problem, because it's my understanding that if you want to handle a double-click, you should be looking for the second mouse up. I am certain that the mouse location is always within the bounds of the view. What could cause this? (Testing on macOS 13.6.4.)
Added: I use a subclass of NSApplication, and override nextEventMatchingMask:untilDate:inMode:dequeue: and sendEvent:. The overrides usually just call through to the superclass method. Logging mouse events from these methods, I see that in the problematic cases, the mouse up events are received from the queue, but never sent.
There's WKWebView.find() method that highlights search result within a WKWebView element on macOS but I don't see any way to clear this highlight. When I search for an empty string is does nothing and the latest search result remains highlighted.
How do we open Keyboard Viewer programatically? I am working on Sonoma Mac Application.
I could open "Emoji & Symbols" programatically as follows.
NSArray *sources = (__bridge NSArray*)TISCreateInputSourceList(nil, false);
TISInputSourceRef keyboardViewer = (__bridge TISInputSourceRef)[sources objectAtIndex: 2]; // "Emoji & Symbols" is the 3rd one. So 2.
TISSelectInputSource(keyboardViewer);
CFRelease((CFTypeRef)sources);
After some searching, Keyboard Viewer could be opened with similiar approach with above in the old previous version of MacOS.
I have a strong feeling there is a way to bring up the keyboard because we can bring up "Emoji & Symbols". I mean, why would apple prevent us to show Keyboard Viewer.
Any idea?
I have a table view where each row has two labels, one left-aligned and one right-aligned. I would like to reload a single row, but doing so causes the right-aligned label to hug the left-aligned label.
Before the reload:
After the reload:
Reloading the whole table view instead, or disabling automatic row height, solves the issue. Can a single row be reloaded without resorting to these two workaround?
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
override func loadView() {
let tableView = NSTableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.delegate = self
tableView.usesAutomaticRowHeights = true
let column = NSTableColumn()
column.width = 400
tableView.addTableColumn(column)
let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.documentView = tableView
view = scrollView
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
print("reload")
tableView.reloadData(forRowIndexes: IndexSet(integer: 2), columnIndexes: IndexSet(integer: 0))
// tableView.reloadData()
}
}
func numberOfRows(in tableView: NSTableView) -> Int {
return 5
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = NSTableCellView()
let textField1 = NSTextField(labelWithString: "hello")
textField1.translatesAutoresizingMaskIntoConstraints = false
let textField2 = NSTextField(wrappingLabelWithString: "world")
textField2.translatesAutoresizingMaskIntoConstraints = false
textField2.alignment = .right
let stack = NSStackView(views: [
textField1,
textField2
])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.distribution = .fill
cell.addSubview(stack)
NSLayoutConstraint.activate([stack.topAnchor.constraint(equalTo: cell.topAnchor, constant: 0), stack.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 0), stack.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: 0), stack.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: 0)])
return cell
}
}
Hello,
I am developing a multi-platform app, and I need an emoji picker. It should be the same as the emoji selection view in the Reminders App.
Reminders App Image:
(A button; when pressed calls the MacOS emoji selector, and the emoji selected is linked to a variable).
I know you can call the EmojiSelector with
NSApp.orderFrontCharacterPalette($variable)
However, it only records the variable if you have a working text field linked to the variable. Then, if you edit the text field you can select more than 1 character, a non-emoji, and the emoji popover is not shown under the button.
How do I make an emoji selector like the one above. Does it require a textfield for the selected emoji to be linked to a variable.
If it does, can the text field be:
Not Viewable and in a ZStack under the button
Only editable by the emoji selector
Replace the current emoji when another is selected
Sorry if my question is lengthy. I have everything else in my app ready, and want to release it to the app store (it will be free).
Thank you for any help,
Dev_Pro
Lately, we are getting a few crash reports ending up with:
NSRangeException
*** -[NSConcreteTextStorage attribute:atIndex:longestEffectiveRange:inRange:]: Range or index out of bounds
The full stack trace is:
Thread 0 Crashed:
0 CoreFoundation 0xfff0177080a6 __exceptionPreprocess
1 libobjc.A.dylib 0xfff016dcd231 objc_exception_throw
2 UIFoundation 0xfff020adce02 -[NSConcreteTextStorage attribute:atIndex:longestEffectiveRange:inRange:]
3 AppKit 0xfff01f051947 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_7.611
4 AppKit 0xfff01f05178e __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_2.605
5 AppKit 0xfff01f04d137 -[NSTextInputContext tryHandleTSMEvent_attributedString_attributedSubstringForProposedRange_withContext:dispatchCondition:dispatchWork:dispatchFurtherCondition:dispatchFurtherWork:continuation:]
6 AppKit 0xfff01e4d37c7 -[NSTextInputContext handleTSMEvent:completionHandler:]
7 AppKit 0xfff01e4d29c8 _NSTSMEventHandler
8 HIToolbox 0xfff02c78f702 DispatchEventToHandlers
9 HIToolbox 0xfff02c78eb4e SendEventToEventTargetInternal
10 HIToolbox 0xfff02c78e9ed SendEventToEventTargetWithOptions
11 HIToolbox 0xfff02c7e7da0 SendTSMEvent_WithCompletionHandler
12 HIToolbox 0xfff02c9404bf __SendTextInputEvent_WithCompletionHandler_block_invoke
13 HIToolbox 0xfff02c93ee07 SendTextInputEvent_WithCompletionHandler
14 HIToolbox 0xfff02c9a06b4 -[IMKInputSession _postEvent:completionHandler:]
15 HIToolbox 0xfff02c9b3997 -[IMKInputSession do_coreAttributesFromRange_postEventLoopWithContext:initBlockEach:postEventCompletionEach:whileConditionBlock:finalCompletion:]
16 HIToolbox 0xfff02c9b4710 __78-[IMKInputSession _coreAttributesFromRange:whichAttributes:completionHandler:]_block_invoke_10
17 HIToolbox 0xfff02c7fc58c DispatchEventToHandlers
18 AppKit 0xfff01f051707 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_7.599
19 AppKit 0xfff01f051412 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_2.593
20 AppKit 0xfff01f04d137 -[NSTextInputContext tryHandleTSMEvent_attributedString_attributedSubstringForProposedRange_withContext:dispatchCondition:dispatchWork:dispatchFurtherCondition:dispatchFurtherWork:continuation:]
21 AppKit 0xfff01e4d37c7 -[NSTextInputContext handleTSMEvent:completionHandler:]
22 AppKit 0xfff01e4d29c8 _NSTSMEventHandler
23 HIToolbox 0xfff02c78f702 DispatchEventToHandlers
24 HIToolbox 0xfff02c78eb4e SendEventToEventTargetInternal
25 HIToolbox 0xfff02c78e9ed SendEventToEventTargetWithOptions
26 HIToolbox 0xfff02c7e7da0 SendTSMEvent_WithCompletionHandler
27 HIToolbox 0xfff02c9404bf __SendTextInputEvent_WithCompletionHandler_block_invoke
28 HIToolbox 0xfff02c93ee07 SendTextInputEvent_WithCompletionHandler
29 HIToolbox 0xfff02c9a06b4 -[IMKInputSession _postEvent:completionHandler:]
30 HIToolbox 0xfff02c9b3997 -[IMKInputSession do_coreAttributesFromRange_postEventLoopWithContext:initBlockEach:postEventCompletionEach:whileConditionBlock:finalCompletion:]
31 HIToolbox 0xfff02c9b39fe __145-[IMKInputSession do_coreAttributesFromRange_postEventLoopWithContext:initBlockEach:postEventCompletionEach:whileConditionBlock:finalCompletion:]_block_invoke
32 HIToolbox 0xfff02c7fc58c DispatchEventToHandlers
33 AppKit 0xfff01f051707 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_7.599
34 AppKit 0xfff01f051412 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_2.593
35 AppKit 0xfff01f04d137 -[NSTextInputContext tryHandleTSMEvent_attributedString_attributedSubstringForProposedRange_withContext:dispatchCondition:dispatchWork:dispatchFurtherCondition:dispatchFurtherWork:continuation:]
36 AppKit 0xfff01e4d37c7 -[NSTextInputContext handleTSMEvent:completionHandler:]
37 AppKit 0xfff01e4d29c8 _NSTSMEventHandler
38 HIToolbox 0xfff02c78f702 DispatchEventToHandlers
39 HIToolbox 0xfff02c78eb4e SendEventToEventTargetInternal
40 HIToolbox 0xfff02c78e9ed SendEventToEventTargetWithOptions
41 HIToolbox 0xfff02c7e7da0 SendTSMEvent_WithCompletionHandler
42 HIToolbox 0xfff02c9404bf __SendTextInputEvent_WithCompletionHandler_block_invoke
43 HIToolbox 0xfff02c93ee07 SendTextInputEvent_WithCompletionHandler
44 HIToolbox 0xfff02c9a06b4 -[IMKInputSession _postEvent:completionHandler:]
45 HIToolbox 0xfff02c9b3997 -[IMKInputSession do_coreAttributesFromRange_postEventLoopWithContext:initBlockEach:postEventCompletionEach:whileConditionBlock:finalCompletion:]
It mostly affects our macOS 14 users who are from China, Hong Kong, and Taiwan - using weird locales most probably.
Is anyone having similar problems?
I'm having an issue with a TextKit2 NSTextView (AppKit). In my subclass's keyDown, I'm doing a bit of manipulation of the textStorage but it seems that if I try to alter any part of the textStorage where a text paragraph and accompanying fragment have already been created, I then get duplicate paragraphs and fragments.
For example, say I want to insert new text at the end of an existing paragraph. I've tried:
Inserting a new attr string (with attrs matching the preceding text) at the end of the existing paragraph text
Replacing the existing paragraph text with a new attr string that includes the new text
First deleting the existing paragraph text and then inserting the new full attr string including the new text
I am wrapping those edits in a textContentStorage.performEditingTransaction closure.
But in all cases, it seems that TextKit 2 wants to create new NSTextParagraph and NSTextFragment objects and doesn't remove the old ones, resulting in duplicate elements in my UI.
Some sample code:
let editLocation = editRange.location
guard editLocation > 0 else {
break
}
let attrs = textStorage.attributes(at: editLocation, effectiveRange: nil)
// paragraphStartLocation is in an NSAttributedString extension not shown
guard let paragraphStartLoc = textStorage.paragraphStartLocation(from: editLocation) else {
assertionFailure(); return
}
var paragraphRange = NSRange(location: paragraphStartLoc, length: editLocation - paragraphStartLoc + 1)
var fullParagraph = textStorage.attributedSubstring(from: paragraphRange).string
fullParagraph += newText
let newAttrStr = NSAttributedString(string: fullParagraph, attributes: attrs)
textContentStorage.performEditingTransaction {
textStorage.deleteCharacters(in: paragraphRange)
textStorage.insert(newAttrStr, at: paragraphStartLoc)
}
I have an NSTextView where I am getting the current position in the text when the textview is clicked. For this, I am using the NSClickGestureRecognizer which calls a selector that grabs the click position from the .location method of the recognizer.
It works as expected however the issue I have is that the click doesn't get recognized by the textView so the insertion point cursor doesn't update in the text view. The actual caret position is updated as if I start typing, the text goes where I last clicked even though the insertion point cursor may be somewhere else.
The documentation states that by default, the delaysPrimaryMouseButtonEvents is set to true when using the recognizer with states that the default event will only trigger on gesture failure which isn't what I want as I always want the default event to pass through so I set it to false when initializing the recognizer.
What happens when I do this is that the default even goes through but the gesture method is never called. If I remove that, it triggers the gesture method but doesn't pass the event through.
It's pretty easy to replicate. Just create a new project with an NSTextView, and use the following ViewController code;
class ViewController: NSViewController, NSTextViewDelegate {
@IBOutlet var textView: NSTextView! {
didSet {
let singleClickGesture = NSClickGestureRecognizer(target: self, action: #selector(singleClickGesture(_:)))
singleClickGesture.numberOfClicksRequired = 1 // single
//If delaysPrimaryMouseButtonEvents set to true or omitted, textView never sets insertion point cursor nor clears any selected text
// but singleClickGesture runs every time
//If delaysPrimaryMouseButtonEvents set to false, textView sets insertion point cursor every time
// but singleClickGesture never runs
// I need the singleClickGesture to run then set the insertion point (Cursor Flashing)
singleClickGesture.delaysPrimaryMouseButtonEvents = false
singleClickGesture.delegate = self
textView.addGestureRecognizer(singleClickGesture)
textView.delegate = self
textView.font = NSFont.systemFont(ofSize: CGFloat(16.0))
self.textView.isSelectable = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
textView.string = """
This is a block of text I will insert into the text view.
It will have multiple lines and will be enough text to reproduce the issue.
"""
}
@objc func singleClickGesture(_ recognizer: NSClickGestureRecognizer) {
print("User clicked in textView")
if recognizer.state == .ended {
let caretLocation = recognizer.location(in: textView)
print("Caret location is: \(caretLocation)")
let cursorPosition = textView.characterIndexForInsertion(at: caretLocation)
print("Cursor position is \(cursorPosition)")
}
}
}
extension ViewController: NSGestureRecognizerDelegate {
}
I've been playing around with this for some time and can't get it to work as I need. If anyone has any suggestion, I would love to hear them.
Thx
Note: This does not happen on MacOS 13 and older.
I have a NSView (parent) and multiple subviews (child nsviews). When I animate the frame of the subviews ex: [[view animator] setFrame:frame] to move them outside the parent view's frame, the contents of the subviews disappear/clipped before the animation starts. This started happening after installing Sonoma. I tried setting clipsToBounds to false and it did not make any difference.
Is anyone else seeing this behavior in Sonoma?
Why does appkit clip the contents before the animation starts? Is there a way to switch it to "clip after animation ends" ?
I currently have a toolbar item group with 3 items, but clicking on any of the items doesn't do anything. Also none of the items appear to be highlighted, not even when manually setting NSToolbarItemGroup.selectedIndex. What am I missing? Setting the action property on the individual items rather than the group makes the items clickable, but still none of them appear to be selected.
class ViewController: NSViewController, NSToolbarDelegate {
let toolbarItemIdentifier = NSToolbarItem.Identifier("group")
let toolbarItemIdentifierItem1 = NSToolbarItem.Identifier("item1")
let toolbarItemIdentifierItem2 = NSToolbarItem.Identifier("item2")
let toolbarItemIdentifierItem3 = NSToolbarItem.Identifier("item3")
override func viewDidAppear() {
let toolbar = NSToolbar()
toolbar.delegate = self
view.window!.toolbar = toolbar
view.window!.toolbarStyle = .expanded
}
func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
return [.flexibleSpace, toolbarItemIdentifier]
}
func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
return [.flexibleSpace, toolbarItemIdentifier, .flexibleSpace]
}
func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
switch itemIdentifier {
case toolbarItemIdentifier:
let item1 = NSToolbarItem(itemIdentifier: toolbarItemIdentifierItem1)
item1.image = NSImage(named: NSImage.addTemplateName)!
item1.label = "add"
let item2 = NSToolbarItem(itemIdentifier: toolbarItemIdentifierItem2)
item2.image = NSImage(named: NSImage.homeTemplateName)!
item2.label = "home"
let item3 = NSToolbarItem(itemIdentifier: toolbarItemIdentifierItem3)
item3.image = NSImage(named: NSImage.pathTemplateName)!
item3.label = "path"
let group = NSToolbarItemGroup(itemIdentifier: itemIdentifier)
group.subitems = [item1, item2, item3]
group.selectionMode = .selectOne
group.selectedIndex = 0
group.target = self
group.action = #selector(selectItem(_:))
return group
default:
return nil
}
}
@objc func selectItem(_ sender: Any) {
print(0)
}
}
On iOS I can create a UIFont that automatically adapts to the font size chosen in the Settings app by the user:
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true
(Copy-pasted from here.) I couldn't find a similar API for macOS. In the Accessibility settings I can change the font size and some apps react to it, like System Settings and Finder automatically increase the labels. Is there a way to create NSFont or NSTextField that automatically adapts to the chosen font size?