Why assigning function.formula = formula does not change function.formula to formula in one go? It's always late one change behind.
struct CustomFunction has defined
.formula as @MainActor.
I feel stupid.
There is a part of code:
struct CustomFormulaView: View {
@Binding var function: CustomFunction
@State var testFormula: String = ""
@EnvironmentObject var manager: Manager
....
.onChange(of: testFormula) {
debugPrint("change of test formula: \(testFormula)")
switch function.checkFormula(testFormula, on: manager.finalSize) {
case .success(let formula):
debugPrint("before Change: \(function.formula)")
function.formula = formula // Nothing happens
debugPrint("Test formula changed: \(testFormula)")
debugPrint("set to success: \(formula)")
debugPrint("what inside function? \(function.formula)")
Task {
//Generate Image
testImage = await function.image(
size: testImageSize),
simulate: manager.finalSize)
debugPrint("test image updated for: \(function.formula)")
}
....
and it produces this output when changed from 0.5 to 1.0
Debug: change of test formula: 1.0
Debug: before Change: 0.5
Debug: Test formula changed: 1.0
Debug: set to success: 1.0
Debug: what inside function? 0.5
Debug: test image updated for: 0.5
0.5 is an old value, function.formula should be 1.0
WT??
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.
Post
Replies
Boosts
Views
Activity
I'm trying to configure the share sheet.
My project uses techniques from the Apple Sample project called CoreDataCloudKitShare which is found here:
https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users#
In this sample code there's a "PersistenceController" which is an NSPersistentCloudKitContainer.
In the "PersistenceController+SharingUtilities" file there are some extensions, and one of them is this:
func configure(share: CKShare, with photo: Photo? = nil) {
share[CKShare.SystemFieldKey.title] = "A cool photo"
}
This text "A cool photo" seems to be the only bespoke configuration of the share sheet within this project.
I want to have more options to control the share sheet, does anyone know how this might be achieved? Thank you!
Hi,
This issue started with iOS 18, in iOS 17 it worked correctly. I think there was a change in SectionedFetchRequest so maybe I missed it but it did work in iOS 17.
I have a List that uses SectionedFetchRequest to show entries from CoreData. The setup is like this:
struct ManageBooksView: View {
@SectionedFetchRequest<Int16, MyBooks>(
sectionIdentifier: \.groupType,
sortDescriptors: [SortDescriptor(\.groupType), SortDescriptor(\.name)]
)
private var books: SectionedFetchResults<Int16, MyBooks>
var body: some View {
NavigationStack {
List {
ForEach(books) { section in
Section(header: Text(section.id)) {
ForEach(section) { book in
NavigationLink {
EditView(book: book)
} label: {
Text(book.name)
}
}
}
}
}
.listStyle(.insetGrouped)
}
}
}
struct EditView: View {
private var book: MyBooks
init(book: MyBooks) {
print("Init hit")
self.book = book
}
}
Test 1: So now when I change name of the Book entity inside the EditView and do save on the view context and go back, the custom EditView is correctly hit again.
Test 2: If I do the same changes on a different attribute of the Book entity the custom init of EditView is not hit and it is stuck with the initial result from SectionedFetchResults.
I also noticed that if I remove SortDescriptor(\.name) from the sortDescriptors and do Test 1, it not longer works even for name, so it looks like the only "observed" change is on the attributes inside sortDescriptors.
Any suggestions will be helpful, thank you.
Hello Apple Developer Community,
I am encountering an issue with app icon rendering after updating an app on devices running iOS 18 or newer. Below are the details:
Issue Summary:
When updating an app from a previous version (with separate light and dark mode icons) to the latest version (where both modes use the same icon), the icon changes are not reflected consistently across all system menus.
Steps to Reproduce:
Set the device mode to Dark Mode.
Install the previous app version (with different icons for light and dark modes).
Update the app to the latest version (where both modes use the same icon).
Change the device mode to Light Mode.
Switch back to Dark Mode.
Expected Behavior:
The app icon should remain consistent across all system menus (Home Screen, Spotlight search, etc.) when switching between Light and Dark Modes.
Observed Behavior:
The app icon displays correctly on the Home Screen but inconsistencies appear in other menus, such as Spotlight search or when toggling between modes.
For instance, in Dark Mode, the icon may revert to the previous black-colored logo or display incorrectly compared to the updated design.
Additional Notes:
The asset catalog is configured correctly, with identical icons set for both light and dark modes in the latest app version.
Incrementing the build number was implemented during the update.
A manual device restart resolves the issue on some devices, but not consistently.
Questions for the Community:
Has anyone else experienced similar app icon caching or rendering issues in iOS 18 or later?
Are there known workarounds or specific configurations to ensure consistent icon rendering across all system menus?
Could this be related to iOS 18's icon caching or appearance handling mechanisms?
Your insights and suggestions would be greatly appreciated. Thank you for your time!
Some crashes were found, not many, but we could not locate the specific code because the error stack is a systematic method.
Error:
NSInternalInconsistencyException
Failed to create remote render context
Stack:
0 CoreFoundation 0x000000018a879d78 ___exceptionPreprocess + 220
1 libobjc.A.dylib 0x00000001a34de734 _objc_exception_throw + 60
2 Foundation 0x000000018c0ff358 -[NSMutableDictionary(NSMutableDictionary) initWithContentsOfFile:] + 0
3 UIKitCore 0x000000018d475f8c ___UIKIT_DID_NOT_RECEIVE_A_REMOTE_CACONTEXT_FROM_COREANIMATION_INDICATING_A_POSSIBLE_BACKBOARDD_CRASH + 572
4 UIKitCore 0x000000018d232484 ___UIKIT_IS_REQUESTING_A_CACONTEXT_FROM_COREANIMATION + 80
5 UIKitCore 0x000000018d1fc32c +[_UIContextBinder createContextForBindable:withSubstrate:] + 708
6 UIKitCore 0x000000018d13bdec -[_UIContextBinder _contextForBindable:] + 148
7 UIKitCore 0x000000018cf5bd20 -[_UIContextBinder updateBindableOrderWithTest:force:] + 480
8 UIKitCore 0x000000018d2e1200 -[_UIContextBinder createContextsWithTest:creationAction:] + 92
9 UIKitCore 0x000000018ccd64c0 -[UIWindowScene _prepareForResume] + 156
10 UIKitCore 0x000000018ce2ef80 -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 876
11 UIKitCore 0x000000018ce72528 -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 288
12 UIKitCore 0x000000018cdfc8c8 -[UIApplicationSceneClientAgent scene:handleEvent:withCompletion:] + 476
13 FrontBoardServices 0x000000019c9dbe18 -[FBSScene updater:didUpdateSettings:withDiff:transitionContext:completion:] + 528
14 FrontBoardServices 0x000000019c9f413c ___94-[FBSWorkspaceScenesClient _queue_updateScene:withSettings:diff:transitionContext:completion:]_block_invoke_2 + 152
15 FrontBoardServices 0x000000019c9d9308 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 240
16 FrontBoardServices 0x000000019c9df824 ___94-[FBSWorkspaceScenesClient _queue_updateScene:withSettings:diff:transitionContext:completion:]_block_invoke + 396
17 libdispatch.dylib 0x000000018a4e0a2c __dispatch_client_callout + 20
18 libdispatch.dylib 0x000000018a4e44e0 __dispatch_block_invoke_direct + 264
19 FrontBoardServices 0x000000019c9dac70 ___FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 48
20 FrontBoardServices 0x000000019c9da040 -[FBSSerialQueue _targetQueue_performNextIfPossible] + 220
21 FrontBoardServices 0x000000019c9de700 -[FBSSerialQueue _performNextFromRunLoopSource] + 28
22 CoreFoundation 0x000000018a89bf04 ___CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
23 CoreFoundation 0x000000018a8acc90 ___CFRunLoopDoSource0 + 208
24 CoreFoundation 0x000000018a7e6184 ___CFRunLoopDoSources0 + 268
25 CoreFoundation 0x000000018a7ebb4c ___CFRunLoopRun + 828
26 CoreFoundation 0x000000018a7ff6b8 _CFRunLoopRunSpecific + 600
27 GraphicsServices 0x00000001a6899374 _GSEventRunModal + 164
28 UIKitCore 0x000000018d164e88 -[UIApplication _run] + 1100
29 UIKitCore 0x000000018cee65ec _UIApplicationMain + 364
30 ??? 0x00000001059b9ce4 0x00000001059b9ce4 + 0
These crashes occurred when the App was about to enter the foreground.
(UIApplicationWillEnterForegroundNotification)
These crashes occurred on systems from 15 to 18.
crash.log
I see this error in the debugger:
#FactoryInstall Unable to query results, error: 5
IPCAUClient.cpp:129 IPCAUClient: bundle display name is nil
Error in destroying pipe Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 5476 on anonymousListener or serviceListener was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 5476 on anonymousListener or serviceListener was invalidated from this process.}
on this function:
func speakItem() {
let utterance = AVSpeechUtterance(string: item.toString())
utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
try? AVAudioSession.sharedInstance().setCategory(.playback)
utterance.rate = 0.3
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
}
When running without the debugger, it will (usually) speak once, then it won't speak unless I tap the button that calls this function many times.
I know AVSpeech has problems that Apple is long aware of, but I'm wondering if anyone has a work around. I was thinking there might be a way to call the destructor for AVSpeechUtterance and generate a new object each time speech is needed, but utterance.deinit() shows: "Deinitializers cannot be accessed"
Thanks in advance for your help! after adding the GooglePlaces package dependency, I added 'import GooglePlaces' to my App.Swift file, and content no longer previews. Thoughts?
I am learning swift ui by mimicing stickies but i am having issue with richtextui
Error
ViewBridge to RemoteViewService Terminated: Error Domain=com.apple.ViewBridge Code=18 "(null)" UserInfo={com.apple.ViewBridge.error.hint=this process disconnected remote view controller -- benign unless unexpected, com.apple.ViewBridge.error.description=NSViewBridgeErrorCanceled}
Why it is connecting to remote service when i develop it in local for mac
UI error is this. I type cursor moves and no text displayed. changed color to everything
some code
import SwiftUI
import AppKit
struct RichTextEditor: NSViewRepresentable {
@Binding var attributedText: NSAttributedString
var isEditable: Bool = true
var textColor: NSColor = .black
var backgroundColor: NSColor = .white
var font: NSFont = NSFont.systemFont(ofSize: 14)
I only started swift ui 2 day ago. Bought mac mini 4 3 day ago to develop ios app but learning mac app first to get experience with mac environment
Who can help
Contact me via discord alexk3434
I need mac developer friends.
In my iOS App I present a QLPreviewController where I want to display a locally stored Video from the iPhone's document directory.
let previewController = QLPreviewController()
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
let url = urlForPreview
return url! as QLPreviewItem
}
This seems to work fine for all but one of my testflight users. He is using an iPhone 12 with iOS18.0.1. The screen becomes unresponsive. He cannot pause the video, share it or close the QLPreviewController.
In his logfile I see the following error...
[AVAssetTrack loadValuesAsynchronouslyForKeys:completionHandler:] invoked with unrecognized keys (
"currentVideoTrack.preferredTransform")
Any ideas?.
The Problem
When transitioning between view controllers that each have their own MTKView but share a Metal renderer backend, we run into delegate ownership conflicts. Only one MTKView can successfully render at a time, since setting the delegate on one view requires removing it from the other, leading to paused views during transitions.
For my app, I need to display the same visuals across multiple views and have them all render correctly.
Current Implementation Approach
I've created a container object that manages the MTKView and its relationship with the shared renderer:
class RenderContainer {
let metalView: MTKView
private let renderer: MetalRenderer
func startRendering() {
metalView.delegate = renderer
metalView.isPaused = false
}
func stopRendering() {
metalView.isPaused = true
metalView.delegate = nil
}
}
View controllers manage the rendering lifecycle in their view appearance methods:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
renderContainer.startRendering()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
renderContainer.stopRendering()
}
Observations & Issues
During view controller transitions, one MTKView must stop rendering before the other can start. Also there is no guarantee that the old view will stop rendering before the new one starts, with the current API design.
This creates a visual "pop" during animated transitions
Setting isPaused = true helps prevent unnecessary render calls but doesn't solve the core delegate ownership problem
The shared renderer maintains its state but can only output to one view at a time
Questions
What's the recommended approach for handling MTKView delegate ownership during animated transitions?
Are there ways to maintain visual continuity without complex view hierarchies?
Should I consider alternative architectures for sharing the Metal content between views?
Any insights for this scenario would be appreciated.
Problem
I am developing a WebDriver agent for automation and using dictionaryRepresentation to retrieve the coordinates of the iOS app hierarchy. However, I am encountering an issue with the accuracy of the x and y coordinates.
Approach Tried
I tested the setup on:
iPhone 12 Pro Max (iOS 16.2): Accuracy issues with the coordinates were observed.
iPhone SE (3rd Generation) (iOS 16.2): Coordinates were accurate for tap actions, with no issues identified.
Observation
It appears that devices with fingerprint biometric authentication provide accurate coordinates.
Can anyone help here to understand is there anything wrong in the code. Are do we have to adjust frame of the element for different devices?
Sample Code
- (NSDictionary *)json_tree
{
NSDictionary<XCUIElementAttributeName, id>
*dictionaryRepresentation = [[self snapshotWithError:nil] dictionaryRepresentation];
return [self.class dictionaryForElementAttributes:dictionaryRepresentation recursive:YES];
}
// This method converts the dictionary to CGRect, handling any broken frame values (e.g., Infinity)
+ (CGRect)handleBrokenFrameFromDict:(id)frameDict {
if ([frameDict isKindOfClass:[NSDictionary class]]) {
CGFloat originX = [frameDict[@"X"] floatValue];
CGFloat originY = [frameDict[@"Y"] floatValue];
CGFloat sizeWidth = [frameDict[@"Width"] floatValue];
CGFloat sizeHeight = [frameDict[@"Height"] floatValue];
CGRect frame = CGRectMake(originX, originY, sizeWidth, sizeHeight);
// Replace Infinity values with CGRectZero
return (isinf(frame.size.width) || isinf(frame.size.height)
|| isinf(frame.origin.x) || isinf(frame.origin.y))
? CGRectZero // or another predefined constant like BROKEN_RECT
: CGRectIntegral(frame);
}
return CGRectZero; // If frameDict is not a valid dictionary, return CGRectZero
}
// This method converts CGRect into a dictionary representation for "rect"
+ (NSDictionary *)rectDictionaryFromCGRect:(CGRect)rect {
return @{
@"x": @(rect.origin.x),
@"y": @(rect.origin.y),
@"width": @(rect.size.width),
@"height": @(rect.size.height)
};
}
+ (NSString *)label:(NSDictionary<XCUIElementAttributeName, id> *)dict
{
XCUIElementType elementType = [dict[XCUIElementAttributeNameElementType] intValue];
NSString *label = dict[XCUIElementAttributeNameLabel];
if (elementType == XCUIElementTypeTextField || elementType == XCUIElementTypeSecureTextField) {
return label;
}
return FBTransferEmptyStringToNil(label);
}
+ (NSString *)name:(NSDictionary<XCUIElementAttributeName, id> *)dict
{
NSString *identifier = dict[XCUIElementAttributeNameIdentifier];
if (nil != identifier && identifier.length != 0) {
return identifier;
}
NSString *label = dict[XCUIElementAttributeNameLabel];
return FBTransferEmptyStringToNil(label);
}
+ (NSString *)value:(NSDictionary<XCUIElementAttributeName, id> *)dict
{
id value = dict[XCUIElementAttributeNameValue];
XCUIElementType elementType = [dict[XCUIElementAttributeNameElementType] intValue];
if (elementType == XCUIElementTypeStaticText) {
NSString *label = [self label:dict];
value = FBFirstNonEmptyValue(value, label);
} else if (elementType == XCUIElementTypeButton) {
NSNumber *isSelected = [dict[XCUIElementAttributeNameSelected] boolValue] ? @YES : nil;
value = FBFirstNonEmptyValue(value, isSelected);
} else if (elementType == XCUIElementTypeSwitch) {
value = @([value boolValue]);
} else if (elementType == XCUIElementTypeTextView ||
elementType == XCUIElementTypeTextField ||
elementType == XCUIElementTypeSecureTextField) {
NSString *placeholderValue = dict[XCUIElementAttributeNamePlaceholderValue];
value = FBFirstNonEmptyValue(value, placeholderValue);
}
value = FBTransferEmptyStringToNil(value);
if (value) {
value = [NSString stringWithFormat:@"%@", value];
}
return value;
}
+ (NSDictionary *)dictionaryForElementAttributes:(NSDictionary<XCUIElementAttributeName, id> *)dict recursive:(BOOL)recursive
{
NSMutableDictionary *info = [[NSMutableDictionary alloc] init];
info[@"type"] = [FBElementTypeTransformer shortStringWithElementType:[dict[XCUIElementAttributeNameElementType] intValue]];
info[@"rawIdentifier"] = FBValueOrNull([dict[XCUIElementAttributeNameIdentifier] isEqual:@""] ? nil : dict[XCUIElementAttributeNameIdentifier]);
info[@"name"] = FBValueOrNull([self name:dict]);
info[@"value"] = FBValueOrNull([self value:dict]);
info[@"label"] = FBValueOrNull([self label:dict]);
// Handle the frame value
CGRect frame = [self handleBrokenFrameFromDict:dict[XCUIElementAttributeNameFrame]];
info[@"frame"] = NSStringFromCGRect(frame);
// Add the rect value
info[@"rect"] = [self rectDictionaryFromCGRect:frame];
info[@"isEnabled"] = [@([dict[XCUIElementAttributeNameEnabled] boolValue]) stringValue];
// visible
// accessible
info[@"isFocused"] = [@([dict[XCUIElementAttributeNameHasFocus] boolValue]) stringValue];
if (!recursive) {
return info.copy;
}
NSArray<NSDictionary<XCUIElementAttributeName, id> *> *childElements = [dict[XCUIElementAttributeNameChildren] isKindOfClass:[NSArray class]] ? dict[XCUIElementAttributeNameChildren] : @[];
if ([childElements count]) {
info[@"children"] = [[NSMutableArray alloc] init];
for (NSDictionary<XCUIElementAttributeName, id> * childSnapshot in childElements) {
[info[@"children"] addObject:[self dictionaryForElementAttributes:childSnapshot recursive:YES]];
}
}
return info;
}
import Cocoa
@available(macOS 10.13, *)
let imagePboardType = NSPasteboard.PasteboardType.fileURL
class DragSourceView: NSImageView {
weak var dragSourceDelegate: NSDraggingSource?
override func mouseDown(with event: NSEvent) {
//拖放数据定义
let pasteboardItem = NSPasteboardItem()
//设置数据的Provider
if #available(macOS 10.13, *) {
pasteboardItem.setDataProvider(self, forTypes: [NSPasteboard.PasteboardType.fileURL])
} else {
// Fallback on earlier versions
}
//拖放item
let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem)
draggingItem.draggingFrame = NSRect(x: 100 , y: 10, width: 100, height: 100)
//拖放可视化图象设置
draggingItem.imageComponentsProvider = {
let component = NSDraggingImageComponent(key: NSDraggingItem.ImageComponentKey.icon)
component.frame = NSRect(x: 0, y: 0, width: 16, height: 16)
component.contents = NSImage(size: NSSize(width: 32,height: 32), flipped: false, drawingHandler: { [unowned self] rect in {
self.image?.draw(in: rect)
return true
}()
}
)
return [component]
}
//开始启动拖放sesson
self.beginDraggingSession(with: [draggingItem], event: event, source: self.dragSourceDelegate!)
}
}
extension DragSourceView: NSPasteboardItemDataProvider {
func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) {
// let data = self.image?.tiffRepresentation
let data = "/Users/slowdony/Desktop/640.jpeg"
let dataUrl = data.data(using: String.Encoding(rawValue: NSUTF8StringEncoding))!
item.setData(dataUrl, forType: type)
}
}
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var sourceView: DragSourceView!
override func viewDidLoad() {
super.viewDidLoad()
self.sourceView.dragSourceDelegate = self
}
}
extension ViewController: NSDraggingSource {
//返回拖放操作类型
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
if (context == .outsideApplication){
return .copy
}
else{
return .generic
}
}
//开始拖放代理回调
func draggingSession(_ session: NSDraggingSession, willBeginAt screenPoint: NSPoint) {
print("draggingSession beginAt \(screenPoint)")
}
//拖放鼠标移动时的代理回调
func draggingSession(_ session: NSDraggingSession, movedTo screenPoint: NSPoint) {
print("draggingSession movedTo \(screenPoint)")
}
//结束拖放代理回调
func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
print("draggingSession endedAt \(screenPoint)")
}
}
I am dragging an image to the desktop through the above code, failed, help
I want to support Genmoji input in my SwiftUI TextField or TextEditor, but looking around, it seems there's no SwiftUI only way to do it?
If none, it's kind of disappointing that they're saying SwiftUI is the path forward, but not updating it with support for new technologies.
Going back, does this mean we can only support Genmoji through UITextField and UIViewRepresentable? or there more direct options?
Btw, I'm also using SwiftData for storage.
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.
Let's say I have a model like this:
@Model
final class DataModel {
var firstProperty: String = ""
}
Later on I create a new property as such:
@Model
final class DataModel {
enum DataEnum {
case dataCase
}
var firstProperty: String = ""
var secondProperty: DataEnum? = .dataCase
}
My expectation is for the data that is already stored, the secondProperty would be added with a default value of .dataCase. However, it's being set to nil instead. I could have sworn it would set to the default value given to it. Has that changed, or has it always been this way? Does this require a migration plan?
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?
Hey guys,
I'm totally new to Swift programming and I'm setting up a view for registering users. I use a VStack to organize the TextFields as well as a DatePicker, but the last one seems to be very rebellious.
Here's my code:
VStack {
TextField("E-Mailadresse", text: $mail)
.frame(height: 30)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.center)
.focused($hasFocus, equals: .mail)
.onKeyPress(.tab, action: {hasFocus = .password; return .handled})
SecureField("Passwort", text: $password)
.frame(height: 30)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.center)
.focused($hasFocus, equals: .password)
.onKeyPress(.tab, action: {hasFocus = .name; return .handled})
TextField("Name", text: $name)
.frame(height: 30)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.center)
.focused($hasFocus, equals: .name)
.onKeyPress(.tab, action: {hasFocus = .prename; return .handled})
TextField("Vorname", text: $prename)
.frame(height: 30)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.center)
.focused($hasFocus, equals: .prename)
.onKeyPress(.tab, action: {hasFocus = .birthday; return .handled})
DatePicker("Geb.:", selection: $birthday, displayedComponents: [.date])
.datePickerStyle(.wheel)
.clipped()
//.focused($hasFocus, equals: .birthday)
Button("Registrieren") {self.register()}
.padding(.top, 20)
.keyboardShortcut(.defaultAction)
}
.frame(width: 375)
}
And this is how it looks like:
As you can see, neither is the DatePicker centered correctly (it's more left located) nor is it clipped (reduced). I also tried adding a .frame() to itself, then I was ably to reduce it to the preferred height, but I can' reduce its width and as a result of this, I can also not write a full label like "Date of Birth" or something, because the wheel of the DatePicker always overlays it...
Is that a kind of misbehavior or am I missing something?
Thank you very much in anticipation for your feedback!
Kind regards
Kevin
Hey guys,
I'm totally unexperienced in Swift coding and I'm doing my first steps using Swift Playgrounds on my macOS as well as on my iPadOS.
I'm setting up a simple App that can be divided in 4 main categories (Splash, Authentication, Content, Setup). Each category (except the Splash as the short intro when running the app) can have a NavigationStack (e. g. switching between login view, register view, forgott password view in authentication). So I thought about having a root view for each of them. My google research gave me lots of ways and hints but it's not clear at all for me if I should and how I should do this. I often read about a RootViewController but I guess that's UIKit stuff and nothing for SwiftUI. Then I read about delegates and such. Then, I read an article that exactly fits my goals and I just liked to get your opinion what you think about this way to solve my plan:
First of all, I define a separate class for a appRootManager:
final class appRootManager: ObservableObject {
enum eRootViews {
case Splash, Authentification, Content, Setup
}
@Published var currentRoot: eRootViews = .Splash
}
The main app file looks like this:
@main
struct MyApp: App {
@StateObject private var oRootManager = appRootManager()
var body: some Scene {
WindowGroup() {
Group {
switch oRootManager.currentRoot {
case .Splash:
viewSplash()
case .Authentification:
viewLogin()
case .Content:
viewContent()
case .Setup:
viewSetup()
}
}
.environmentObject(oRootManager)
.modelContainer(for: [Account.self])
}
}
}
In each of the for root view files (e. g. Splash view) I make the appRootManager addressable and switch the root view by updating the enum value, like for example:
struct viewSplash: View {
@EnvironmentObject private var oRootManager: appRootManager
var body: some View {
ZStack {
Color.blue
.ignoresSafeArea()
Text("Hello World")
.font(.title)
.fontWeight(.semibold)
.foregroundColor(.white)
}
.onAppear() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
withAnimation(.spring()) {oRootManager.currentRoot = .Authentification}
}
}
}
}
It works fine and does exactly what I like to have (when I run the app out of Swift Playgrounds). I'm just wondering why it does not work in the App Preview in Swift Playgrounds and this is why I'd like to have your opinion to the way I solve my plan.
I'm very happy for any feedback. Thanks a lot in anticipation!
Kind regards
Kevin
Exploring Live Activity feature for Apple Watch right now and found that it has this default view with "Open on iPhone" button when you tap Live Activity. That button perfectly brings iOS app to foreground as if you tapped iOS's Live Activity.
Is there a way to mimic that behavior from inside Watch app code? From inside WKApplicationDelegate, for example
Tried openSystemURL but it seems lile it's only available for tel or sms links
Hello,
I am using SwiftUI ShareLink to share an image with Instagram app, but when I select "Story" option in share interface, an error happens, "Error: Something went wrong".
Has anyone had this problem? Is there a solution?
Thanks
Thanks