I want to get the content present in a note or a mail thread when my cursor is in it on macos. (In the focused element).
But I don't succeed to get any element from both mail and notes using :
let result = AXUIElementCopyAttributeValue(appRef, kAXFocusedUIElementAttribute as CFString, &focusedElement)
Even when I want to check the available attribute :
let result = AXUIElementCopyAttributeNames(element, &attributeNames)
I got AXUIElementCopyAttributeNames result: AXError(rawValue: -25204)
But I have the write permission because when I am running AXIsProcessTrusted() to see if I got accessible permission it don't throw an error
Is it possible to do it that way or I have to change
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
When working with SwiftUI TabView and ScrollView at root level with scrollPosition(id:anchor:), after tapping on Tab item the ScrollView scrolls to the top, but the scroll position ID does not get updated.
struct ContentView: View {
@State var positionID: Int?
var body: some View {
TabView {
Tab("Test", systemImage: "house") {
ScrollView(.vertical) {
LazyVStack(pinnedViews: [.sectionHeaders]) {
ForEach(0 ... 100, id: \.self) { index in
Text("\(index)")
}
}
.scrollTargetLayout()
}
.scrollPosition(id: $positionID, anchor: .top)
.onChange(of: positionID) { _, newValue in
print(newValue)
}
}
}
}
}
FB15964820
I'm seeing a discrepancy in the metrics of the "New York" system font returned from various Macs. Here's a sample (works well in Playgrounds):
import Cocoa
let font = NSFont(descriptor: .preferredFontDescriptor(forTextStyle: .body).withDesign(.serif)!, size: NSFont.systemFontSize)!
print("\(font.fontName) \(font.pointSize)")
print("ascender: \(font.ascender)")
let layoutManager = NSLayoutManager()
print("lineHeight: \(layoutManager.defaultLineHeight(for: font))")
When I run this on multiple Macs, I get two types of different results. Some – most Macs – report this:
.NewYork-Regular 13.0
ascender: 12.3779296875
lineHeight: 16.0
However, when I run on my own Mac (and also on the one of a colleague), I get this instead:
.NewYork-Regular 13.0
ascender: 14.034145955454255
lineHeight: 19.0
It's clearly the same font in the same point size. Yet the font has different metrics, causing a layout manager to also compute a significantly different line height.
So far I've found out that neither CPU generation/architecture nor macOS version seem to play a role. This issue has been reproducible since at least macOS 14. Having just migrated to a new Mac, the issue is still present.
This does not affect any other system or commonly installed font. It's only New York (aka the serif design).
So I assume this must be something with my setup. Yet I have been unable to find anything that may cause this. Anybody have some ideas? Happy to file a bug report but wanted to check here first.
I'm building an app that lets users create charts with custom values and while testing, I came up with this bug that happens when the view width forces the legend to have more than 1 line. Due to Swift trying to align the different labels vertically, it's forcing the first line to overflow.
Here's the code to generate this:
import SwiftUI
import Charts
struct DonutView: View {
var countries:[(country:String, count:Int)] = [
(country: "Africa", count: 54),
(country: "Asia", count: 48),
(country: "Europe", count: 44),
(country: "North America", count: 23),
(country: "Oceania", count: 14),
(country: "South America", count: 12),
]
var body: some View {
Chart {
ForEach(0..<countries.count, id:\.self) { idx in
SectorMark(
angle: .value(countries[idx].country, countries[idx].count),
innerRadius: .ratio(0.5)
)
.foregroundStyle(by: .value("label", countries[idx].country))
}
}
.frame(width: 310, height: 270)
.border(.blue, width: 1)
}
}
Has anyone seen this? Is there a solution?
I know about building custom legends, but SwiftUI has no wrapping HStack nor VStack, and the app allows users to change the legend position from the bottom to the top or sides. If I were to go this way, I'd have to write a very large chunk of code to bypass what seems to be a bug.
My app has a sort of "HUD" that sits at the top of the screen. It contains some general information about gameplay, and a couple of interactive elements: a scrolling list of text and a button.
It's imbedded into the main view like this:
struct WindowedInGameView: View {
@Environment(GameModel.self) private var gameModel
var body: some View {
ZStack(alignment: .top) {
VStack {
HUDTopView()
switch(gameModel.game?.location.player_location)
{
case .plaza:
PlazaView()
case .city_hall:
CityHallView()
///... Lots of additional views...
default:
Text("Player is in unknown location.")
}
// --> Position 2
}
if gameModel.showConversationView {
... an overlay for NPC conversations...
}
if (gameModel.showNotificationView)
{
.. a notification overlay...
}
}
}
}
If HUDTopView() is at the indicated place at the top of the VStack, none of its interactive elements work: you can't press buttons, you can't scroll the text. Everything looks present and interactive, it just doesn't seem to receive any input.
If I move HUDTopView() to the bottom of the VStack (where the comment indicates "Position 2") it works just fine, except it's not where I want it to be located. So far as I can tell, its position alone is disabling it somehow.
In either case, any interactive elements in the views from the switch are acting fine, regardless of their position relative to the HUD view.
This fails in the same way on iOS, iPadOS, and macOS. (The visionOS implementation doesn't use this main view, so I haven't tried it there).
What it isn't:
the overlays at the bottom. Commenting them out doesn't change behaviour.
the ZStack - I can replace it with an HStack, and it still fails.
Anything about the container of this view -- it fails in preview
Anything about the HUDTopView() -- a simple button placed there becomes noninteractive, too.
I'm at a complete loss for what could possibly be causing this.
Topic:
UI Frameworks
SubTopic:
SwiftUI
How to do content transition when one image is a system symbol and the other is in assets catalouge?
I have a save button:
Button(action: {
saveTapped()
}) {
Label("Save", systemImage: wasSaved ? "checkmark" : "square.and.arrow.down")
}
.contentTransition(.symbolEffect(.replace))
.disabled(wasSaved)
Now, I created a new custom icon and added it into the assets catalogue: "custom.square.and.arrow.down.badge.checkmark" for when the wasSaved state is true. The issue I am facing is that to use it I need to use the method of Label with image:, while to use the non custom symbol, I need to use systemImage:.
So how is it possible to transition between the two?
How can I make this appear inside the NavigationSplitView toolbar?
It doubles up with the close button and takes up space...
App Main view
import SwiftUI
@main
struct WritingApp: App
{
var body: some Scene
{
DocumentGroup(newDocument: WritingAppDocument())
{ file in
StoryView(document: file.$document)
}
}
}
Story view
import SwiftUI
struct StoryView: View
{
@Binding var document: WritingAppDocument
@State private var isShowingSheet = false
@FocusState private var isFocused: Bool
var body: some View
{
NavigationSplitView
{
Text("Sidebar")
}
detail:
{
HStack
{
Text("Detail View")
}
.toolbar
{
ToolbarItem
{
Button("Book", systemImage: "book")
{
}
}
ToolbarItem
{
Button("Circle", systemImage: "circle")
{
}
}
}
}
}
}
I properly copy a scrFile to a dstFile with
mManager = [NSFileManager defaultManager];
[mManager copyItemAtPath:srcPath toPath:dstPath error:&error];
but on "some destination disks" the dstFile gets a modificationDate with truncated milliseconds. For instance, with this format
"yyyy.MM.dd - HH:mm:ss:SSS" I visualize
srcDate = 2024.11.03 - 12:42:35:772
dstDate = 2024.11.03 - 12:42:35:000
After the copyItemAtPath I even unsuccessfully tried to set the dstFile modificationDate this way
NSMutableDictionary *dstAttrs = [NSMutableDictionary dictionaryWithDictionary:[mManager attributesOfItemAtPath:dstPath error:nil]];
[dstAttrs setObject:srcDate forKey:NSFileModificationDate];
[mManager setAttributes:dstAttrs ofItemAtPath:dstPath error:nil];
Again, the dstDate is 2024.11.03 - 12:42:35:000.
I unsuccessfully tried even
FSSetCatalogInfo(&dstRef, fsInfo, &srcFsCatInfo);
No way. I noticed that the destination disk is an USB External Physical Volume, Mac OS Extended (Journaled) with "Ignore Ownership on this volume" on. Could this flag be the cause of the trouble? Shouldn't this flag regard only the files ownership?
This issue brings another trouble. Since the srcDate and the dstDate are not equal, my macOS app performing a backup, copies the srcFile to the dstFile again and again.
To workaround the trouble, I actually compare srcDate with dstDate after truncating their milliseconds. But I guess this is not a good practice.
Any idea on how to fix this trouble? Thanks.
P.S. I attach here the disk info
Disk_Info.txt
Hi!
SiriTipView(intent:) shows the first phrase for my App Shortcut, but unlike ShortcutsLink(), does not use the localized applicationName. Hence the phrase shown does not work 😬
Is this a known limitation, any workarounds?
In a SwiftUI macOS application, when removing the title bar by setting window.titleVisibility to .hidden and window.titlebarAppearsTransparent to true, the title bar space is still accounted for in the window height. This results in a delta (red area) in the height of the window that cannot be ignored by usual SwiftUI view modifiers like .edgesIgnoringSafeArea(.top). My actual view is the blue area.
I want to have the view starting in the top safeArea and the window to be the exact size of my view. I am struggling to achieve this. I have also tried with window.styleMask.insert(.fullSizeContentView) to no effect.
Can I get some help? 🙂
Here is my source code to reproduce this behavior:
windowApp.swift
@main
struct windowApp: App {
@NSApplicationDelegateAdaptor private var appDelegate: AppDelegate
var body: some Scene {
WindowGroup {
ContentView()
.edgesIgnoringSafeArea(.top)
.background(.red)
.border(.red)
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
if let window = NSApplication.shared.windows.first {
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.styleMask.insert(.fullSizeContentView)
}
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.frame(minWidth: 400, minHeight: 200)
.background(.blue)
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
My xamarin application running fine in iOS 17 and below versions. but in iOS 18 and above when I open application and then when I use it for few min it gets crashed automatically and does not even show any crash report in mobile. When I checked the console logs in XCode then I found out that One error is logging more than 700 times in a sec. that is why the application is crashing. I will attach the error below.
Modifying properties of a view's layer off the main thread is not allowed: view <Xamarin_Forms_Platform_iOS_FrameRenderer: 0x7f9605e5e7a0> with nearest ancestor view controller <Xamarin_Forms_Platform_iOS_GroupableItemsViewController_1: 0x7f9605f96dc0>; backtrace:
(
0 UIKitCore 0x0000000152d29c00 -[UIView(UIKitManual) _raiseExceptionForBackgroundThreadLayerPropertyModification] + 453
1 UIKitCore 0x0000000152d2a188 -[UIView(UIKitManual) actionForLayer:forKey:] + 609
2 QuartzCore 0x0000000126f731da -[CALayer actionForKey:] + 151
3 QuartzCore 0x0000000126f7a425 ZN2CA5Layer12begin_changeEPNS_11TransactionEjP11objc_objectRS4 + 199
4 QuartzCore 0x0000000126f7ead8 _ZN2CA5Layer6setterEj12_CAValueTypePKv + 974
5 QuartzCore 0x0000000126f727e9 -[CALayer setOpacity:] + 49
6 Leadrat.Mobile.Forms.iOS 0x0000000101122fc9 xamarin_dyn_objc_msgSend + 217
7 ??? 0x00000001a315f176 0x0 + 7031091574
8 ??? 0x00000001b312d0bb 0x0 + 7299322043
9 ??? 0x000000019d76712b 0x0 + 6936752427
10 Mono 0x000000010b9b70b5 mono_jit_runtime_invoke + 1621
11 Mono 0x000000010bbac1e8 mono_runtime_invoke_checked + 136
12 Mono 0x000000010bbb1c9d mono_runtime_delegate_try_invoke + 157
13 Mono 0x000000010bbd0957 start_wrapper_internal + 647
14 Mono 0x000000010bbd06ae start_wrapper + 62
15 libsystem_pthread.dylib 0x000000012a21018b _pthread_start + 99
16 libsystem_pthread.dylib 0x000000012a20bae3 thread_start + 15
Am displaying a number of annotations on a map which vary their location over time and can inherently cluster together. I'd like to be able to set the Z order on the annotations as I have simple logic how to order them in the Z direction.
I see the ZPriority property on UIKit Annotation view, but unclear how I can do that in SwiftUI. Is this exposed in any manner?
I thought I could create a viewModifier and using the content parameter I'd be able to drop down into the UIKIt view to apply the value to the property, but alas I'm not seeing a clear way to do so.
Is this at all possible without dropping down entirely to creating a NSViewRepresentable/UIViewRepresentable implementation of Map?
My ipAd app is now crashing when being run on a Mac (with designed for iPad emulator). It. has been working a month ago, today was first time I tried in awhile.
I get a warning
"It's not legal to call -layoutSubtreeIfNeeded on a view which is already being laid out. If you are implementing the view's -layout method, you can call -[super layout] instead. Break on void _NSDetectedLayoutRecursion(void) to debug. This will be logged only once. This may break in the future."
shortly after that the App Crashes.
Thread 1: EXC_BAD_ACCESS (code=1, address=0x14a0839653d0)
The crash happens when my main view (in a Tab view) goes to a DetailView. I stripped out all functionality in my code and it still happens
mainView
NavigationLink{ ImageDetailView2 () } label: { img }
struct ImageDetailView2: View {
var body: some View {
Text("Hello, World!")
}
}
Any help would be appreciated
Topic:
UI Frameworks
SubTopic:
SwiftUI
My app's top crash is a mysterious one and I can't seem to figure it out. It always crashes on
_objc_fatalv(unsigned long long, unsigned long long, char const*, char*)
But the stack traces include a few different possible culprits like
NavigationBridge_PhoneTV.pushTarget(isDetail:)
UIKitNavigationBridge.update(environment:)
ViewRendererHost.updateGraph()
UIScrollView(SwiftUI) _swiftui_adjustsContentInsetWhenScrollDisabled
Crash reports here:
2024-12-02_21-37-21.7864_-0600-1e78918e5586309b96a1c2986ff722778dec8a77.crash
2024-12-02_19-18-29.1251_-0500-a2fc5513683cd647b4adbbe03cc59e4a09237b5f.crash
2024-12-01_11-59-09.8888_-0500-9eb224ab3d37e76d0b966ea83473f584ac3bbe18.crash
2024-11-28_17-17-38.4808_+0100-46208989f016fbefd16c30873a88c2ef61dd91a1.crash
Hopefully someone here can shed some light. For context we use a lot of UIHostingController's to bridge our SwiftUI views.
I'm running into an issue with using .topBarTrailing placement for a toolbar item. The app fails to launch (crashes) with this placement. The following view works fine with any other placement (other than .topBarLeading).
What am I doing wrong?
var body: some View {
NavigationStack {
Text("Overview")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button {
// noop
} label: {
Label("Add", systemImage: "plus")
}
}
}
.navigationTitle("Overview")
.navigationBarTitleDisplayMode(.inline)
}
}
I've opted to use .confirmationAction as a workaround, which works fine. It also positions the toolbar item in the same place on the view as the .topBarTrailing placement would.
I'm using Xcode version 15.0 and targeting WatchOS 10.
Verbose error output when trying to run the app in the simulator:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Layout requested for visible navigation bar, <PUICStackedNavigationBar: 0x100e1e8d0; baseClass = UINavigationBar; frame = (0 0; 198 60); opaque = NO; autoresize = W; layer = <CALayer: 0x60000027c280>> delegate=0x101877800 standardAppearance=0x60000261cc60, when the top item belongs to a different navigation bar. topItem = <UINavigationItem: 0x100f11230> title='Overview' style=navigator, navigation bar = <PUICStackedNavigationBar: 0x100f22a80; baseClass = UINavigationBar; frame = (0 0; 198 60); opaque = NO; autoresize = W; layer = <CALayer: 0x6000002887c0>> delegate=0x101069600 standardAppearance=0x60000261f3c0, possibly from a client attempt to nest wrapped navigation controllers.'
I'm trying to push a SwiftUI view from UIKit using UIHostingController. In the new view there is a button in the right side of the navigation bar, but it pops after the push animation. I can't make it appear with an animation like in a normal UIViewController.
I tried adding the button in the navigationItem of the hosting controller and in the toolbar of the SwiftUI but none gives a smooth animation.
I've made a small test and this are the results.
This is the code:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Home"
}
@IBAction func buttonNavPressed(_ sender: Any) {
let vc = UIHostingController(rootView: ContentView())
vc.navigationItem.title = "NavItem Button"
vc.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(sayHello))
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func buttonSwiftUIPressed(_ sender: Any) {
let vc = UIHostingController(rootView: ContentViewWithButton())
navigationController?.pushViewController(vc, animated: true)
}
@objc func sayHello() {
print("Hello")
}
}
struct ContentView: View {
var body: some View {
Text("No button")
}
}
struct ContentViewWithButton: View {
var body: some View {
Text("With button")
.navigationTitle("SwuitUI W Button")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button(action: { print("Hello") },
label: { Image(systemName: "camera") }
)
}
}
}
}
There is any workaround to this problem?
I have a tip that's supposed to be shown after a certain event:
extension Tips {
static let somethingHappened = Tip.Event(id: "somethingHappened")
}
struct TestTip: Tip {
let title = Text("Test tip")
let message = Text("This is a description")
var rules: [Rule] {
#Rule(Tips.somethingHappened) { $0.donations.count > 0 }
}
}
I would like to present this tip when its status becomes .available. To do this, I'm observing statusUpdates in a task:
tipStatusObserverTask = Task { [tip, weak self] in
print("observing \(tip.id)")
for await status in tip.statusUpdates {
guard let self, !Task.isCancelled else {
return
}
print("tip status: \(status)")
if case .available = status {
print("will present \(tip.id)")
displayTip()
}
}
print("done observing \(tip.id)")
}
then I'm donating the event on a button press:
@objc func didPressButton() {
Tips.somethingHappened.sendDonation {
print("donated Tips.somethingHappened")
}
}
The event is donated, but statusUpdates doesn't fire, so the tip never gets shown. The tip appears after I restart the app. What's happening? What am I doing wrong?
statusUpdates fires just fine if the rule is based on a @Parameter change, so I would expect this approach to work for event-based rules.
Here's a project that reproduces the issue in case anyone wants to try: https://www.icloud.com/iclouddrive/085FxcgTPStDSSPoXwh7dx1pQ#TipKitTest
In MacOS app I present modally NSTableView.
The table is created in IB and its data and functionality are handled in corresponding NSViewController.
As long as the positioning of modally presented table is left to the system, the tableview is placed in the center of the presenting view controller and everything works fine.
But if I apply NSLayoutConstraints to position it as I need for visual design reasons, the table stops responding to mouse clicks.
Here's the code inside the presenting view controller:
bookmarks_TVC = Bookmarks_TVC()
bookmarks_TVC.view.translatesAutoresizingMaskIntoConstraints = false
self.present(bookmarks_TVC, animator: ModalPresentationAnimator())
NSLayoutConstraint.activate([
self.bookmarks_TVC.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant:410),
self.bookmarks_TVC.view.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 170)
])
Once again, without NSLayoutConstraints the table responds as expected. Once the constraints are added, it becomes unresponsive.
Thanks in advance for any helpful suggestions.
Topic:
UI Frameworks
SubTopic:
AppKit
Is there any way to prevent the keyboard from bouncing when changing the focus state in onSubmit? Or is it not recommended to change focus in onSubmit?
The following view is setup so that pressing return on the keyboard should cause focus to move between the TextFields.
struct TextFieldFocusState: View {
enum Field {
case field1
case field2
}
@FocusState var focusedField: Field?
var body: some View {
Form {
TextField("Field 1", text: .constant(""))
.focused($focusedField, equals: .field1)
.onSubmit { focusedField = .field2 }
TextField("Field 2", text: .constant(""))
.focused($focusedField, equals: .field2)
.onSubmit { focusedField = .field1 }
}
}
}
I would expect that when pressing return, the keyboard would say on screen.
What actually happens is the keyboard appears to bounce when the return key is pressed (first half of gif). I assume this is because onSubmit starts dismissing the keyboard then setting the focus state causes the keyboard to be presented again.
The issue doesn't occur when tapping directly on the text fields to change focus (second half of gif).
I am encountering an issue where the Share Extension in my app fails to launch intermittently.
In my project, NSExtensionPrincipalClass is set to ComposeShellVC. When the Share Extension launches successfully, the following log entry appears, indicating that ComposeShellVC is being created:
09:21:09.339190+0800 2254529 ViewServices com.apple.UIKit compose-shareextension
Received request to create view controller: self: <_UIViewServiceViewControllerOperator: 0x109194c00>;
class: compose_shareextension.ComposeShellVC; contextToken: 42EA1BDB-5CDF-4EBD-8503-8A9A04BCE41C
However, when the bug happens, this entry is absent during the failed launches. Additionally, I am unable to set breakpoints within the Share Extension to further investigate.
Could you provide guidance on the next steps to diagnose this issue? Any advice on debugging techniques or tools that can help pinpoint the cause of this behavior would be greatly appreciated.