I introduced lottie to toggle in my widget to show a transition animation, but found that the.json file wouldn't load. The loading_hc.json file is validated and exists in the widget target. Ask for help, thank you!
struct LottieView: UIViewRepresentable {
let animationName: String
func makeUIView(context: Context) -> LOTAnimationView {
let lotAnimationView = LOTAnimationView(name: animationName, bundle: .main)
lotAnimationView.contentMode = .scaleAspectFit
lotAnimationView.play()
return lotAnimationView
}
func updateUIView(_ uiView: LOTAnimationView, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
}
struct ControlToggleDisarmingStyle: ToggleStyle {
func makeBody(configuration: Configuration) -> some View {
if configuration.isOn {
LottieView(animationName: "loading_hc.json").foregroundColor(.clear).frame(width: 24,height: 24)
} else {
Image("icon_disarm", bundle: Bundle.main).foregroundColor(.clear)
}
}
}
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi, I'm new to software development and facing a problem that don't know how to solve.
I have a piece of code using .backgroundPreferenceValue and .anchorPreference modifiers to monitor a button's position while dragging. It works perfectly on preview, simulator, and my own device if I download it through a cable connected to my computer. However, today I distributed it to TestFlight and found out it broke. I repeated the process serval times but the result is still the same. Has anybody run into the same type of problem before? Desperately need help. Many many thanks!
Topic:
App Store Distribution & Marketing
SubTopic:
TestFlight
Tags:
Swift Packages
SwiftUI
TestFlight
I am trying to discover how to display my application’s calculated Solar Information values in a chart.
My application identifies a selected location in MapKit.
The application identifies the location’s longitude, latitude, and current time of day.
The application calculates the selected location’s NOAA [SOLAR ELEVATION], and the [SOLAR AZIMUTH] for the time of day.
The application calculates the data, then stores the calculated values as a [Plist] file within my application’s Document Directory.
For the moment, complete with repeated scouring of the Internet, I am not sure how to properly convert, transfer, or create a Structure, required by the chart to display the calculated values. I would like to create the chart once the calculations are complete, but I introduced a Plist to store the calculations for future use, too.
The calculated values coincide with the NOAA Solar Calculations, complete to the displayed [h : m : s], whereas I also designed the application to create the [Array of Dictionary Objects] to store the calculated values for each subsequent six minute interval, until the end of the selected location’s day. The calculated values are properly appended to the [Array of Dictionary Objects] after each completed calculation, with data transfer constants. There are 240 calculations per day from [00:06:00 to 23:54:00], presented as a [STRING], complete with the [Elevation] presented as a [DOUBLE].
For example :: The application generates the following [Calculated Array of Dictionary Objects], then recreates, and appends a new Plist in the Document Directory.
mySolarElevationDataArrayOfDictionaries :: [(theRequiredTimeOfDay: "00:06:00", theCalculatedElevation: -62.60301082991259), (theRequiredTimeOfDay: "00:12:00", theCalculatedElevation: -62.94818095051292), (theRequiredTimeOfDay: "00:18:00", theCalculatedElevation: -63.245198186807215), (theRequiredTimeOfDay: "00:24:00", theCalculatedElevation: -63.49236786176319), (theRequiredTimeOfDay: "00:30:00", theCalculatedElevation: -63.688223890934175), (theRequiredTimeOfDay: "00:36:00", theCalculatedElevation: -63.831564163806945), (theRequiredTimeOfDay: "00:42:00", theCalculatedElevation: -63.921486675739004), (theRequiredTimeOfDay: "00:48:00", theCalculatedElevation: -63.95741610687708), to the end of the data :: ===> (theRequiredTimeOfDay: "23:54:00", theCalculatedElevation: -60.69355458181633)]
The application presents the initial data as follows ::
Then presents a compass view to illustrate the results ::
I modified the Chart’s [MOCK DATA] from the calculated values to test the Chart’s display in a [SwiftUI Hosting Controller].
For example :: The following Chart Mock Data in a [HourlySunElevation_MockChartData.swift] file is called by the application’s [Content View].
import Foundation
struct Value {
let theRequiredTimeOfDay: String
let theCalculatedElevation: Double
static func theSunElevationMockData() -> [Value] {
return [Value(theRequiredTimeOfDay: "00:06:00", theCalculatedElevation: -62.60301082991259), Value(theRequiredTimeOfDay: "00:12:00", theCalculatedElevation: -62.94818095051292), Value(theRequiredTimeOfDay: "00:18:00", theCalculatedElevation: -63.245198186807215), Value(theRequiredTimeOfDay: "00:24:00", theCalculatedElevation: -63.49236786176319), Value(theRequiredTimeOfDay: "00:30:00", theCalculatedElevation: -63.688223890934175), Value(theRequiredTimeOfDay: "00:36:00", theCalculatedElevation: -63.831564163806945), Value(theRequiredTimeOfDay: "00:42:00", theCalculatedElevation: -63.921486675739004), Value(theRequiredTimeOfDay: "00:48:00", theCalculatedElevation: -63.95741610687708), to the end of the data :: ===> Value(theRequiredTimeOfDay: "23:54:00", theCalculatedElevation: -60.69355458181633)]
The Chart illustrates the Mock Data as follows ::
I also created a Struct within the [MySunElevationChart_ViewController] to try to append the calculated data, using the same logic with the Plist data transfer constants, as employed by the [Array of Dictionary Objects] ::
struct ChartSolarElevationValues {
var theRequiredTimeOfDay: String
var theCalculatedElevation: Double
// Structs have an implicit [init]. This is here for reference.
init(theRequiredTimeOfDay: String, theCalculatedElevation: Double) {
self.theRequiredTimeOfDay = theRequiredTimeOfDay
self.theCalculatedElevation = theCalculatedElevation
//mySolarElevationChartData.append(self)
} // End of [init(theRequiredTimeOfDay: String, theCalculatedElevation: Double)]
} // End of [struct ChartSolarElevationValues]
Unfortunately, the result did not append each subsequent calculation, but continued to create the same calculation as a new distinct object ::
NOTE :: I only called three calculations with the Struct test.
// NOTE :: To prevent an [ERROR] at [var mySolarElevationChartData = [ChartSolarElevationValues]] since it has an init.
// Therefore you must add () at the end of [var mySolarElevationChartData = [ChartSolarElevationValues]]
let theData = [ChartSolarElevationValues]()
//print("theData :: \(theData)\n")
let someData = ChartSolarElevationValues(theRequiredTimeOfDay: TheTimeForDaySunElevation.theTheTimeForDaySunElevation, theCalculatedElevation:VerifyCityLocationSearchRequestCorrectedSolarElevation.theVerifyCityLocationSearchRequestCorrectedSolarElevation)
var theData_New = theData
theData_New.append(someData)
print("theData_New :: \(theData_New)\n")
// Prints :: theData_New :: [My_Map.ChartSolarElevationValues(theRequiredTimeOfDay: "00:06:00", theCalculatedElevation: -61.11000735370401)]]
// Prints :: [theData_New :: [My_Map.ChartSolarElevationValues(theRequiredTimeOfDay: "00:12:00", theCalculatedElevation: -61.315092082911875)]]
// Prints :: [theData_New :: [My_Map.ChartSolarElevationValues(theRequiredTimeOfDay: "00:18:00", theCalculatedElevation: -61.47403413313205)]]
So, I am misintepreting the required coding structure to properly append the Elevation Chart, and the Azimuth Chart with the calculated data.
I know something is amiss, but for the moment, I do not know how to address this issue.
Your suggestions would be welcome ... :]
jim_k
Hi everyone,
I'm working on a SwiftUI app and need help building a view that integrates the device's camera and uses a pre-trained Core ML model for real-time object recognition. Here's what I want to achieve:
Open the device's camera from a SwiftUI view.
Capture frames from the camera feed and analyze them using a Create ML-trained Core ML model.
If a specific figure/object is recognized, automatically close the camera view and navigate to another screen in my app.
I'm looking for guidance on:
Setting up live camera capture in SwiftUI.
Using Core ML and Vision frameworks for real-time object recognition in this context.
Managing navigation between views when the recognition condition is met.
Any advice, code snippets, or examples would be greatly appreciated!
Thanks in advance!
I'm trying to implement a 3 column NavigationSplitView in SwiftUI on macOS - very similar to Apple's own NavigationCookbook sample app - with the slight addition of multiple sections in the sidebar similar to how the Apple Music App has multiple sections in the sidebar.
Note: This was easily possible using the deprecated
NavigationLink(tag, selection, destination) API
The most obvious approach is to simply do something like:
NavigationSplitView(sidebar: {
List {
Section("Section1") {
List(section1, selection: $selectedItem1) {
item in
NavigationLink(item.label, value: item)
}
}
Section("Section2") {
List(section2, selection: $selectedItem2) {
item in
NavigationLink(item.label, value: item)
}
}
}
},
content: {
Text("Content View")
}, detail: {
Text("Detail View")
})
But unfortunately, this doesn't work - it doesn't seem to properly iterate over all of the items in each List(data, selection: $selected) or the view is strangely cropped - it only shows 1 item. However if the 1 item is selected, then the appropriate bindable selection value is updated. See image below:
If you instead use ForEach for enumerating the data, that does seem to work, however when you use ForEach, you loose the ability to track the selection offered by the List API, as there is no longer a bindable selection propery in the NavigationLink API.
NavigationSplitView(sidebar: {
List {
Section("Section1") {
ForEach(section1) {
item in
NavigationLink(item.label, value: item)
}
}
Section("Section2") {
ForEach(section2) {
item in
NavigationLink(item.label, value: item)
}
}
}
},
content: {
Text("Content View")
}, detail: {
Text("Detail View")
})
We no longer know when a sidebar selection has occurred.
See image below:
Obviously Apple is not going to comment on the expected lifespan of the now deprecated API - but I am having a hard time switching to the new NavigationLink with a broken sidebar implementation.
Am in the process of migrating some UIKit based apps over to SwiftUI, but for the life of me I cannot find the SwiftUI equivalent of Readable Content Margins.
I have come across some workarounds that kind of, sort of work, but do not produce the same results when compared to running the same user interface written using UIKit on several sizes of iPads in portrait and landscape orientiations.
is it something Apple has not gotten around to yet, because I realize SwiftUI is a work-in-progress, or do we not care about creating consistent readable margins in our apps anymore?
When I try to launch a ShareLink from within a fullScreenCover, I get the following error:
Attempt to present <UIActivityViewController: 0x105e6a400> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x1053a37c0> (from <_TtGC7SwiftUI19UIHostingControllerVVS_7TabItem8RootView_: 0x105eb8a00>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x114890000>
Seems like a bug, has anyone else encountered this or found a way around it?
I have developed a mobile app using SwiftUI. Now I am in the process of building a CarPlay application. I know how to test the CarPlay app using a simulator but here is my confusion,
How to test the iPhone app and CarPlay together? I want to test few scenarios like, user login / logout from mobile app. Location enabled /disabled in the mobile app.
I know that swiftUI handles the scenes by itself. Kindly help me validate the above scenarios as I am getting black screen on iPhone whenever the CarPlay is launched. Below is the code snippet,
func application(_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions) -> UISceneConfiguration {
if connectingSceneSession.role == .carTemplateApplication {
let sceneConfiguration = UISceneConfiguration(name: "CarPlay Scene", sessionRole: connectingSceneSession.role)
sceneConfiguration.delegateClass = CarPlaySceneDelegate.self
return sceneConfiguration
}
// Configuration for other types of scenes
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
.preferredColorScheme(.light)
}
}
}
Info.plist
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<true/>
<key>UISceneConfigurations</key>
<dict>
<key>CPTemplateApplicationSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>CarPlay Scene</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).CarPlaySceneDelegate</string>
</dict>
</array>
</dict>
</dict>
I have a very cheap Bluetooth-connected printer. And I want to print out a word or two via Core Bluetooth. It's an iOS app with the SwiftUI framework. The following is what I have for an ObservableObject class.
import Foundation
import CoreBluetooth
class BluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {
@Published var connectedDevices: [CBPeripheral] = []
@Published var powerOn = false
@Published var peripheralConnected = false
private var centralManager: CBCentralManager!
private var peripheralName = "LX-D02"
private var connectedPeripheral: CBPeripheral?
private var writeCharacteristic: CBCharacteristic?
private let serviceUUID = CBUUID(string:"5833FF01-9B8B-5191-6142-22A4536EF123")
private let characteristicUUID = CBUUID(string: "FFE1")
override init() {
super.init()
self.centralManager = CBCentralManager(delegate: self, queue: nil)
}
func startScanning() {
if centralManager.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
powerOn = true
print("Bluetooth is powered on")
} else {
print("Bluetooth is not available")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if !connectedDevices.contains(peripheral) {
if let localName = advertisementData["kCBAdvDataLocalName"] as? String {
if localName == peripheralName {
connectedDevices.append(peripheral)
centralManager.connect(peripheral, options: nil)
centralManager.stopScan()
peripheralConnected = true
print("Connected: \(peripheral.identifier.uuidString)")
}
}
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
connectedPeripheral = peripheral
peripheral.delegate = self
let services = [serviceUUID]
peripheral.discoverServices(services)
//discoverServices(peripheral: peripheral)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: (any Error)?) {
guard let error = error else {
print("Failed connection unobserved")
return
}
print("Error: \(error.localizedDescription)")
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let error = error {
print("Failing to discover servies: \(error.localizedDescription)")
return
}
discoverCharacteristics(peripheral: peripheral)
}
/* Return all available services */
private func discoverServices(peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
}
private func discoverCharacteristics(peripheral: CBPeripheral) {
guard let services = peripheral.services else {
return
}
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard let characteristics = service.characteristics else {
return
}
for characteristic in characteristics {
let characteristicUUID = characteristic.uuid
print("Discovered characteristic: \(characteristicUUID)")
peripheral.setNotifyValue(true, for: characteristic)
if characteristic.properties.contains(.writeWithoutResponse) {
writeCharacteristic = characteristic
print("You can write!!!") // Never read...
}
if characteristic.properties.contains(.write) {
print("You can write?")
writeCharacteristic = characteristic // Being read...
}
}
func writeToPrinter() {
guard let peripheral = connectedPeripheral else {
print("Ughhh...")
return
}
if let characteristic = writeCharacteristic {
if let data = "Hello".data(using: .utf8, allowLossyConversion: true) {
peripheral.writeValue(data, for: characteristic, type: .withoutResponse)
peripheral.writeValue(data, for: characteristic, type: .withResponse) // -> Message sent successfully
}
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
print("Writing error: \(error.localizedDescription)")
return
}
print("Message sent successfully")
}
}
My app has no trouble connecting to the bluetooth-connected printer. Initially, I called
discoverServices(peripheral:)
to get all services And I get a service identifier (5833FF01-9B8B-5191-6142-22A4536EF123) for my printer. peripheral(_:didDiscoverCharacteristicsFor:error:) doesn't return a thing for .writeWithoutResponse but does return a characteristic for .write. Eventually, if I call writeToPrinter(),
peripheral.writeValue(data, for: characteristic, type: .withoutResponse)
returns
WARNING: Characteristic <CBCharacteristic: 0x3019040c0, UUID = 5833FF02-9B8B-5191-6142-22A4536EF123, properties = 0x8, value = (null), notifying = NO> does not specify the "Write Without Response" property - ignoring response-less write
If I call
peripheral.writeValue(data, for: characteristic, type: .withResponse)
, there is no error. But I get no output from the printer. What am I doing wrong? Thanks.
macOS 15 includes a neat section in System Preferences Settings to change the dynamic text size, as outlined see: https://support.apple.com/guide/mac-help/make-text-and-icons-bigger-mchld786f2cd/mac
However, it's not immediately clear a) how to get one's app in this list, and b) if the usual methods from iOS to react to text size even work on macOS. Does anyone have any experience here? Or should I implement my own controls in my app's settings and call it a day?
For context, my app is a macOS-native SwiftUI app.
I have found a system bug with UINavigationController, UIGestureRecognizerDelegate mainly the swipe back control.
I have reproduced this in many apps, while some that use custom swipe back i can not reproduce, however any app using default uikit/swift transitions i can reproduce the flicker/previous screen flashing
The Bug: a slight tap or series of quick taps anywhere on the screen (with the slightest (1-2pt -x)confuse the system into thinking its a swipe back gesture, however instead of pushing back to previous screen the UI flickers and flashes the previous screen. for a split second, very easy to reproduce.
on screens with lots of options of boxes to tap it happens quite often.
I have removed all custom "swipe back from anywhere" logic, all custom gesture logic, and can still reproduce by tapping the edge of the screen
with only UINavigationController, UIGestureRecognizerDelegate in my navigation controller.
Please let me know the best way to get in contact with someone at apple to either build an extension to prevent this flicker or if a developer has a fix but this is rarely talked about. (velocity limits etc do not work, and just make the gesture feel awful)
all the developers i have reached out too have looked into this and have said "its an ios bug, only fix is build a custom swipe back from anywhere, or wait for apple to fix it).... as a small indie app, building my own seems daunting
Recap: quick or taps with small x movement flash previous screen instead of pushing back or simply recognizing it as a tap and not flashing previous screen. this happens with no custom code default uikit/swift. Link me your app i can probably reproduce it, I have reproduced it in X(was hard), Retro(easy), and many more.
The goal is to have a smooth native swipe/drag back from anywhere gesture while preventing flicking on fast taps or short taps with minor x movement. i have tried everything from setting limits to -x, velocity limits etc. nothing fixes this.
happy hacking!
PS i hope someone at apple calls me and i can explain this and we can fix it for every app in an update.
I’m following the example code from Apple to implement the new iPadOS 18 TabView() with the new Tab(). While the tabbing itself is working fine, I can’t get it to show up a (large) navigation title in the sidebar (like the Home or Files app).
I’ve tried placing .navigationTitle("App Name") at the TabView, but that doesn’t work. Is it possible to do this in any way or is this not recommended to show?
TabView {
Tab("Overview", systemImage: "film") {
Text("Put a OverviewView here")
}
TabSection("Watch") {
Tab("Movies", systemImage: "film") {
Text("Put a MoviesView here")
}
Tab("TV Shows", systemImage: "tv") {
Text("Put a TVShowsView here")
}
}
TabSection("Listen") {
Tab("Music", systemImage: "music.note.list") {
Text("Put a MusicView here")
}
Tab("Podcasts", systemImage: "mic") {
Text("Put a PodcastsView here")
}
}
}
.tabViewStyle(.sidebarAdaptable)
.navigationTitle("App Name")
.navigationBarTitleDisplayMode(.large)
I know that there is also the .tabViewSidebarHeader() modifier, but that adds any view above the scroll view content. Neither does that easily allow to make it look like the regular navigation title, nor does it actually display in the navigation bar at the top, when scrolling down.
Hi,
I'm not sure why but when my fileURL is .jpg file and I drop the file from my app to Finder folders it make the dropped file as .jpeg
Is there a way to fix it?
[.onDrag {
if FileManager.default.fileExists(atPath: file.path) {
// Provide the file as an item for dragging
let fileURL = URL(fileURLWithPath: file.path)
let itemProvider = NSItemProvider(contentsOf: fileURL)
// Remove the file extension in the suggestedName
let baseNameWithoutExtension = fileURL.deletingPathExtension().lastPathComponent
itemProvider?.suggestedName = baseNameWithoutExtension
return itemProvider ?? NSItemProvider()
} else {
// Handle the case where the file no longer exists
print("File no longer exists at path: \(file.path)")
return NSItemProvider()
}
})
Hello everyone,
I am a beginner in programming and recently encountered an interesting issue in SwiftUI. (I must admit that it might not be a bug and could simply be due to my lack of understanding.)
I have extracted the relevant code that causes this behavior. Here's the code:
struct BugView: View {
var body: some View {
List {
VStack {
Button("Bug") {
print("1")
}
Button("Bug") {
print("2")
}
Button("Bug") {
print("3")
}
}
}
}
}
In this view, clicking any of the buttons results in all of them being triggered simultaneously. As a result, the console outputs:
1
2
3
I would appreciate it if someone could help me understand why this happens and how to fix it. Thanks in advance!
I feel like I must be missing something dumb, but I can't figure it out. I'm trying to create a modifier to make items resizable by dragging on the corner (I haven't actually implemented the corner part yet though so dragging anywhere on the object resizes it). However the rate that I'm dragging at is different from the rate that the object is resizing. It's also different for horizontal and vertical translation (the horizontal change is smaller than the rate that I'm dragging while the vertical change is larger).
Any help would be greatly appreciated!
Here's my code for the modifier:
struct Resizable: ViewModifier {
@State var size: CGSize = CGSize(width: 500, height: 500)
@State var activeSize: CGSize = .zero
func body(content: Content) -> some View {
content
.frame(width: abs(size.width + activeSize.width), height: abs(size.height + activeSize.height))
// offset is so the top right corner doesn't move
.offset(x: -abs(size.width + activeSize.width) / 2, y: abs(size.height + activeSize.height) / 2)
.gesture(
DragGesture()
.onChanged { gesture in
activeSize.width = -gesture.translation.width
activeSize.height = gesture.translation.height
}
.onEnded { _ in
size.width += activeSize.width
size.height += activeSize.height
activeSize = .zero
}
)
}
}
extension View {
func resizable(maxSize: CGSize = .zero) -> some View {
modifier(Resizable())
}
}
And it is used like so:
struct ContentView: View {
var body: some View {
Rectangle()
.fill(Color.blue)
.resizable()
}
}
Hi,
I have the following swiftUI code:
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.colorEffect(ShaderLibrary.AlphaConvert())
and the following shader:
[[ stitchable ]] half4 AlphaConvert(float2 position, half4 currentColor) {
return half4(currentColor.r>0.5,currentColor.r<=0.5,0,(currentColor.r>0.5));
}
I am loading a full-res image from my photo library (24MP)... The image initially displays fine, with portions of the image red, and the rest black (due to alpha blending)... However, after rotating the device, I get an image that is a combination of red&green... Note, that the green pixels from the shader have alpha 0, hence, should never be seen. Is there something special that needs to be done on orientation changes so that the shader works fine?
Apparently, settings do not show anymore the apps settings in iOS 18.2.
I tested on simulators (Xcode 16.2) both on iOS 18.1 and iOS 18.2 and got very different results:
In iOS 18.1 simulator, I see the settings of a lot of apps.
In iOS 18.2 simulator, not a single app setting.
That is a really serious issue in simulator for development (I filed a bug report FB16175635), but would be really critical on device as it would make it impossible to adjust setting of many apps.
Unless I missed something (meta setting ?) in iOS 18.2 ?
I have not upgraded to 18.2 notably for this reason. So I would appreciate if someone who has upgraded could make the test and report ?
select Settings on Home page
scroll to Apps category
tap here to access the list
Does the list show anything ?
Thanks for your help.
Hi! After upgrading to Xcode 16.1 my watchOS app is getting below error using a DatePicker configured with: displayedComponents: .hourAndMinute. I cannot find a solution for this error/warning. It only appears when im using : .hourAndMinute or : .hourAndMinuteandSeconds, but not .date. Note! My code is unchanged only change I Xcode upgrade. Any suggestions?
ForEach<Array, Array, _ConditionalContent<_ConditionalContent<_ConditionalContent<_ConditionalContent<YearPicker, MonthPicker>, _ConditionalContent<DayPicker, ComponentPicker>>, _ConditionalContent<_ConditionalContent<ComponentPicker, ComponentPicker>, _ConditionalContent<AMPMPicker, ModifiedContent<Text, _PaddingLayout>>>>, EmptyView>>: the ID [":"] occurs multiple times within the collection, this will give undefined results!
import SwiftUI
import WidgetKit
struct TimeEditView: View {
let title: String
@Binding var storedValue: String
var body: some View {
Form {
DatePicker(
title,
selection: Binding<Date>(
get: { Date.from(storedValue) ?? Date() },
set: { newDate in
storedValue = newDate.toString()
}
),
displayedComponents: .hourAndMinute
)
.onChange(of: storedValue) {
WidgetCenter.shared.reloadAllTimelines()
print("Morning Start changed!")
}
}
.navigationTitle(title)
}
}
These helper methods allow to use modifier methods in standard for SwiftUI short way.
extension View {
@inline(__always)
func modify(_ block: (_ view: Self) -> some View) -> some View {
block(self)
}
@inline(__always)
func modify<V : View, T>(_ block: (_ view: Self, _ data: T) -> V, with data: T) -> V {
block(self, data)
}
}
_
DISCUSSION
Suppose you have modifier methods:
func addBorder(view: some View) -> some View {
view.padding().border(Color.red, width: borderWidth)
}
func highlight(view: some View, color: Color) -> some View {
view.border(Color.red, width: borderWidth).overlay { color.opacity(0.3) }
}
_
Ordinar Decision
Your code may be like this:
var body: some View {
let image = Image(systemName: "globe")
let borderedImage = addBorder(view: image)
let highlightedImage = highlight(view: borderedImage, color: .red)
let text = Text("Some Text")
let borderedText = addBorder(view: text)
let highlightedText = highlight(view: borderedText, color: .yellow)
VStack {
highlightedImage
highlightedText
}
}
This code doesn't look like standard SwiftUI code.
_
Better Decision
Described above helper methods modify(:) and modify(:,with:) allow to write code in typical for SwiftUI short way:
var body: some View {
VStack {
Image(systemName: "globe")
.modify(addBorder)
.modify(highlight, with: .red)
Text("Some Text")
.modify(addBorder)
.modify(highlight, with: .yellow)
}
}
System provides AnyShape type erasure that animates correctly. But system doesn't provide AnyInsettableShape. Here is my implementation of AnyInsettableShape (and AnyAnimatableData that is needed to support animation).
Let me know if there is simpler solution.
struct AnyInsettableShape: InsettableShape {
private let _path: (CGRect) -> Path
private let _inset: (CGFloat) -> AnyInsettableShape
private let _getAnimatableData: () -> AnyAnimatableData
private let _setAnimatableData: (_ data: AnyAnimatableData) -> AnyInsettableShape
init<S>(_ shape: S) where S : InsettableShape {
_path = { shape.path(in: $0) }
_inset = { AnyInsettableShape(shape.inset(by: $0)) }
_getAnimatableData = { AnyAnimatableData(shape.animatableData) }
_setAnimatableData = { data in
guard let otherData = data.rawValue as? S.AnimatableData else { assertionFailure(); return AnyInsettableShape(shape) }
var shape = shape
shape.animatableData = otherData
return AnyInsettableShape(shape)
}
}
var animatableData: AnyAnimatableData {
get { _getAnimatableData() }
set { self = _setAnimatableData(newValue) }
}
func path(in rect: CGRect) -> Path {
_path(rect)
}
func inset(by amount: CGFloat) -> some InsettableShape {
_inset(amount)
}
}
struct AnyAnimatableData : VectorArithmetic {
init<T : VectorArithmetic>(_ value: T) {
self.init(optional: value)
}
private init<T : VectorArithmetic>(optional value: T?) {
rawValue = value
_scaleBy = { factor in
(value != nil) ? AnyAnimatableData(value!.scaled(by: factor)) : .zero
}
_add = { other in
AnyAnimatableData(value! + (other.rawValue as! T))
}
_subtract = { other in
AnyAnimatableData(value! - (other.rawValue as! T))
}
_equal = { other in
value! == (other.rawValue as! T)
}
_magnitudeSquared = {
(value != nil) ? value!.magnitudeSquared : .zero
}
_zero = {
AnyAnimatableData(T.zero)
}
}
fileprivate let rawValue: (any VectorArithmetic)?
private let _scaleBy: (_: Double) -> AnyAnimatableData
private let _add: (_ other: AnyAnimatableData) -> AnyAnimatableData
private let _subtract: (_ other: AnyAnimatableData) -> AnyAnimatableData
private let _equal: (_ other: AnyAnimatableData) -> Bool
private let _magnitudeSquared: () -> Double
private let _zero: () -> AnyAnimatableData
mutating func scale(by rhs: Double) {
self = _scaleBy(rhs)
}
var magnitudeSquared: Double {
_magnitudeSquared()
}
static let zero = AnyAnimatableData(optional: nil as Double?)
@inline(__always)
private var isZero: Bool { rawValue == nil }
static func + (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> AnyAnimatableData {
guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return .zero }
return lhs._add(rhs)
}
static func - (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> AnyAnimatableData {
guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return .zero }
return lhs._subtract(rhs)
}
static func == (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> Bool {
guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return true }
return lhs._equal(rhs)
}
@inline(__always)
private static func fillZeroTypes(_ lhs: AnyAnimatableData, _ rhs: AnyAnimatableData) -> (AnyAnimatableData, AnyAnimatableData)? {
switch (!lhs.isZero, !rhs.isZero) {
case (true, true): (lhs, rhs)
case (true, false): (lhs, lhs._zero())
case (false, true): (rhs._zero(), rhs)
case (false, false): nil
}
}
}