Applying glass effect, providing a shape isn't resulting in the provided shape rendering the interaction correctly.
.glassEffect(.regular.tint(Color(event.calendar.cgColor)).interactive(), in: .rect(cornerRadius: 20))
results in properly drawn view but interactive part of it is off. light and shimmer appear as a capsule within the rect.
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
I have added multiple status icons to my project, in the form of .icon files created with Icon Composer. The main app icon works, but the status icons are not working.
I am attempting to load the images from the asset catalog using NSImage imageNamed:, and apply them to the NSApp dockTile using NSGlassEffectContainerView. I don't even know if that attempt is going to work, as I never get past the stage of NSImage loading the icons.
Maybe someone on the forums knows what to do there? I'd be willing to use one of my coding support incidents to work through this if necessary, as my two incidents will expire as my subscription rolls over in August anyway.
My project lives at https://github.com/losnoco/cog/, and the Tahoe attempt WIP lives in the wip.tahoe branch, with the latest commit as of this post being the attempt to adapt the Dock Icon generation.
I'd love to know if I can adapt this easily. I'm also still trying to support existing non-Glass custom .png icons the user can add to their profile folder with buttons in the preferences, as well as supporting legacy status icons on pre-Tahoe installs. I also try to add a progress bar to the dock tile view when the app is processing something at length.
Hello. I want to use an icon created with Icon Composer to change the app icon in my iOS 26 app.
UIApplication.shared.setAlternateIconName("AppIcon")
This code works with the icon included in Assets.xcassets (AppIconOld) and the default icon specified in Info.plist (AppIcon.icon), but it does not work with another icon (AppIconRed.icon).
All icon names (AppIconOld, AppIcon, AppIconRed) are included in the “Alternate App Icon Sets” in Build Settings.
Also, I can’t display the .icon file as an image. If I use the old method to load it as a UIImage, the image is retrieved, but its appearance is not accurate.
Topic:
UI Frameworks
SubTopic:
SwiftUI
The example code below shows what I am trying to achieve: When the user types a '*', it should be replaced with a '×'.
It looks like it works, but the cursor position is corrupted, even though it looks OK, and the diagnostics that is printed below shows a valid index. If you type "12*34" you get "12×43" because the cursor is inserting before the shown cursor instead of after.
How can I fix this?
struct ContentView: View {
@State private var input: String = ""
@State private var selection: TextSelection? = nil
var body: some View {
VStack {
TextField("Type 12*34", text: $input, selection: $selection)
.onKeyPress(action: {keyPress in
handleKeyPress(keyPress)
})
Text("Selection: \(selectionAsString())")
}.padding()
}
func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result {
if (keyPress.key.character == "*") {
insertAtCursor(text: "×")
moveCursor(offset: 1)
return KeyPress.Result.handled
}
return KeyPress.Result.ignored
}
func moveCursor(offset: Int) {
guard let selection else { return }
if case let .selection(range) = selection.indices {
print("Moving cursor from \(range.lowerBound)")
let newIndex = input.index(range.lowerBound, offsetBy: offset, limitedBy: input.endIndex)!
let newSelection : TextSelection.Indices = .selection(newIndex..<newIndex)
if case let .selection(range) = newSelection {
print("Moved to \(range.lowerBound)")
}
self.selection!.indices = newSelection
}
}
func insertAtCursor(text: String) {
guard let selection else { return }
if case let .selection(range) = selection.indices {
input.insert(contentsOf: text, at: range.lowerBound)
}
}
func selectionAsString() -> String {
guard let selection else { return "None" }
switch selection.indices {
case .selection(let range):
if (range.lowerBound == range.upperBound) {
return ("No selection, cursor at \(range.lowerBound)")
}
let lower = range.lowerBound.utf16Offset(in: input)
let upper = range.upperBound.utf16Offset(in: input)
return "\(lower) - \(upper)"
case .multiSelection(let rangeSet):
return "Multi selection \(rangeSet)"
@unknown default:
fatalError("Unknown selection")
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
How to achieve the same navigation bar style as in the Design foundations from idea to interface - WWDC25 video?
Screenshot: https://imgur.com/a/huzsm1H
There's no new navigationBarTitleDisplayMode that has action buttons aligned with the title.
Logic Pro recently changed the way it accepts drag and drop. If the ItemProvider contains UTType.midi, then Logic Pro shows visual feedback for the drop operation, but when the item is dropped, nothing happens. In the past, drag-and-drop used to work. With today's version (Logic Pro 11.2), the only way I was able to successfully drop MIDI was to provide UTType.fileURL and no other data types. But that's not a viable solution; I need other data types to be included too.
As a side note, I tested with Ableton Live 12 and it works with no issue.
Is this a bug in Logic Pro? What ItemProvider structure does Logic Pro expect to correctly receive the MIDI data?
What is UI Scene lifecycle all about?
Where is more information about this?
Topic:
UI Frameworks
SubTopic:
UIKit
I'm trying to make a Swift Chart where 24 AreaMarks an hour apart on X axis over a day display a vertical gradient.
The gradient is vertical and is essentially [Color.opacity(0.1),Colour,Color.opacity(0.1]
The idea here is where the upper and lower points of each AreaMark are the same or close to each other in the Y axis, the chart essentially displays a line, where they are far apart you get a nice fading vertical gradient.
However, it seems that the .alignsMarkStylesWithPlotArea modifier is always set for AreaMarks even if manually applying it false.
Investigating further, I've learnt that with AreaMarks in a series, Swift Charts seems to only listen to the first foreground style set in. I've created some sample code to demonstrate this.
struct DemoChartView: View {
var body: some View {
Chart {
AreaMark(x: .value("Time", Date().addingTimeInterval(0)), yStart: .value("1", 40), yEnd: .value("2", 60))
.foregroundStyle(LinearGradient(colors: [.pink, .teal], startPoint: .top, endPoint: .bottom))
.alignsMarkStylesWithPlotArea(false)
AreaMark(x: .value("Time", Date().addingTimeInterval(3600)), yStart: .value("1", 44), yEnd: .value("2", 58))
.foregroundStyle(LinearGradient(colors: [.orange, .yellow], startPoint: .top, endPoint: .bottom))
.alignsMarkStylesWithPlotArea(false)
AreaMark(x: .value("Time", Date().addingTimeInterval(03600*2)), yStart: .value("1", 50), yEnd: .value("2", 90))
.foregroundStyle(LinearGradient(colors: [.green, .blue], startPoint: .top, endPoint: .bottom))
.alignsMarkStylesWithPlotArea(false)
}
}
}
Which produces this:
So here, all the different .foregroundStyle LinearGradients are being ignored AND the .alignsMarkStylesWithPlotArea(false) is also ignored - the amount of pink on the first mark is different to the second and third 🤷♂️
Has anyone encountered this. Are AreaMarks the correct choice or are they just not setup to create this type of data display. Thanks
.glassProminent not working, but .glass works for .buttonStyle()
as used here
https://youtu.be/3MugGCtm26A?si=dvo2FeE88OnNIwI9&t=938
/Users/brianruiz/repos/taskss/taskss/Views/Components/EmptyStateView.swift:125:39 Reference to member 'glassProminent' cannot be resolved without a contextual type
if #available(iOS 26.0, *) {
Button(action: {
HapticManager.shared.selection()
action()
}) {
Text(buttonLabel ?? "Action")
.frame(maxWidth: .infinity)
}
.padding(.horizontal, 24)
.buttonStyle(.glassProminent)
.buttonBorderShape(.capsule)
.controlSize(.large)
.tint(.primary)
.offset(y: buttonOffset)
.opacity(buttonOpacity)
.scaleEffect(isPressed ? 0.95 : 1.0)
.animation(.bouncy(), value: isPressed)
.onLongPressGesture(minimumDuration: .infinity, maximumDistance: 50, pressing: { pressing in
isPressed = pressing
}, perform: {})
.onAppear {
guard animate else { return }
withAnimation(.bouncy().delay(0.6)) {
buttonOffset = 0
buttonOpacity = 1
}
}
} else {
// Fallback on earlier versions
}
I'm implementing infinite scrolling with Swift Charts where additional historical data loads when scrolling near the beginning of the dataset. However, when new data is loaded, the chart's scroll position jumps unexpectedly.
Current behavior:
Initially loads 10 data points, displaying the latest 5
When scrolling backwards with only 3 points remaining off-screen, triggers loading of 10 more historical points
After loading, the scroll position jumps to the 3rd position of the new dataset instead of maintaining the current view
Expected behavior:
Scroll position should remain stable when new data is loaded
User's current view should not change during data loading
Here's my implementation logic using some mock data:
import SwiftUI
import Charts
struct DataPoint: Identifiable {
let id = UUID()
let date: Date
let value: Double
}
class ChartViewModel: ObservableObject {
@Published var dataPoints: [DataPoint] = []
private var isLoading = false
init() {
loadMoreData()
}
func loadMoreData() {
guard !isLoading else { return }
isLoading = true
let newData = self.generateDataPoints(
endDate: self.dataPoints.first?.date ?? Date(),
count: 10
)
self.dataPoints.insert(contentsOf: newData, at: 0)
self.isLoading = false
print("\(dataPoints.count) data points.")
}
private func generateDataPoints(endDate: Date, count: Int) -> [DataPoint] {
var points: [DataPoint] = []
let calendar = Calendar.current
for i in 0..<count {
let date = calendar.date(
byAdding: .day,
value: -i,
to: endDate
) ?? endDate
let value = Double.random(in: 0...100)
points.append(DataPoint(date: date, value: value))
}
return points.sorted { $0.date < $1.date }
}
}
struct ScrollableChart: View {
@StateObject private var viewModel = ChartViewModel()
@State private var scrollPosition: Date
@State private var scrollDebounceTask: Task<Void, Never>?
init() {
self.scrollPosition = .now.addingTimeInterval(-4*24*3600)
}
var body: some View {
Chart(viewModel.dataPoints) { point in
BarMark(
x: .value("Time", point.date, unit: .day),
y: .value("Value", point.value)
)
}
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: 5 * 24 * 3600)
.chartScrollPosition(x: $scrollPosition)
.chartXScale(domain: .automatic(includesZero: false))
.frame(height: 300)
.onChange(of: scrollPosition) { oldPosition, newPosition in
scrollDebounceTask?.cancel()
scrollDebounceTask = Task {
try? await Task.sleep(for: .milliseconds(300))
if !Task.isCancelled {
checkAndLoadMoreData(currentPosition: newPosition)
}
}
}
}
private func checkAndLoadMoreData(currentPosition: Date?) {
guard let currentPosition,
let earliestDataPoint = viewModel.dataPoints.first?.date else {
return
}
let timeInterval = currentPosition.timeIntervalSince(earliestDataPoint)
if timeInterval <= 3 * 24 * 3600 {
viewModel.loadMoreData()
}
}
}
I attempted to compensate for this jump by adding:
scrollPosition = scrollPosition.addingTimeInterval(10 * 24 * 3600)
after viewModel.loadMoreData(). However, this caused the chart to jump in the opposite direction by 10 days, rather than maintaining the current position.
What's the problem with my code and how to fix it?
Hello, I am wondering if it is possible to have a Line Mark with different line styles. I am trying to create a Line Mark where part of the line is solid and another part of the line is dashed. Even with a conditional it only displays one or the other. Is it currently possible in SwiftCharts to do something like the attached image? Thank you.
If you try to add a graph for a function in Apple Notes you can see that numbers marking coordinates are positioned along the axes (see screenshot 1).
But when I am making my own plot view with Swift Charts I don't see that option. Marks for X axis are positioned at the bottom, and marks for Y axis are positioned to the right. I don't see an API that can configure them to be shown along the axes.
Is there something that I am missing? Or is Apple just using some private API for that?
I could make a custom overlay to display these marks, but then I will have to adjust them while zooming myself, which can be problematic.
Hello there!
I wanted to give a native scrolling mechanism for the Swift Charts Graph a try and experiment a bit if the scenario that we try to achieve might be possible, but it seems that the Swift Charts scrolling performance is very poor.
The graph was created as follows:
X-axis is created based on a date range,
Y-axis is created based on an integer values between moreless 0-320 value.
the graph is scrollable horizontally only (x-axis),
The time range (x-axis) for the scrolling content was set to one year from now date (so the user can scroll one year into the past as a minimum visible date (.chartXScale).
The X-axis shows 3 hours of data per screen width (.chartXVisibleDomain).
The data points for the graph are generated once when screen is about to appear so that the Charts engine can use it (no lazy loading implemented yet).
The line data points (LineMark views) consist of 2880 data points distributed every 5 minutes which simulates - two days of continuous data stream that we want to present. The rest of the graph displays no data at all.
The performance result:
The graph on the initial loading phase is frozen for about 10-15 seconds until the data appears on the graph.
Scrolling is very laggy - the CPU usage is 100% and is unacceptable for the end users.
If we show no data at all on the graph (so no LineMark views are created at all) - the result is similar - the empty graph scrolling is also very laggy.
Below I am sharing a test code:
@main
struct ChartsTestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
Spacer()
}
}
}
struct LineDataPoint: Identifiable, Equatable {
var id: Int
let date: Date
let value: Int
}
actor TestData {
func generate(startDate: Date) async -> [LineDataPoint] {
var values: [LineDataPoint] = []
for i in 0..<(1440 * 2) {
values.append(
LineDataPoint(
id: i,
date: startDate.addingTimeInterval(
TimeInterval(60 * 5 * i) // Every 5 minutes
),
value: Int.random(in: 1...100)
)
)
}
return values
}
}
struct ContentView: View {
var startDate: Date {
return endDate.addingTimeInterval(-3600*24*30*12) // one year into the past from now
}
let endDate = Date()
@State var dataPoints: [LineDataPoint] = []
var body: some View {
Chart {
ForEach(dataPoints) { item in
LineMark(
x: .value("Date", item.date),
y: .value("Value", item.value),
series: .value("Series", "Test")
)
}
}
.frame(height: 200)
.chartScrollableAxes(.horizontal)
.chartYAxis(.hidden)
.chartXScale(domain: startDate...endDate) // one year possibility to scroll back
.chartXVisibleDomain(length: 3600 * 3) // 3 hours visible on screen
.onAppear {
Task {
dataPoints = await TestData().generate(startDate: startDate)
}
}
}
}
I would be grateful for any insights or suggestions on how to improve it or if it's planned to be improved in the future.
Currently, I use UIKit CollectionView where we split the graph into smaller chunks of the graph and we present the SwiftUI Chart content in the cells, so we use the scrolling offered there. I wonder if it's possible to use native SwiftUI for such a scenario so that later on we could also implement some kind of lazy loading of the data as the user scrolls into the past.
Hi!
I'm building an app that uses Swift Charts to visualize stock market data, and I'm encountering a couple of issues.
The stock API I’m using provides data only for the trading days when the market is open. The problem is that I need to skip over the missing dates (non-trading days) in the chart, but still keep the x-axis formatted correctly (e.g., group ticks by month). If I convert the dates to String to handle missing data, I lose the correct x-axis formatting, and the date labels become inaccurate among with its data.
Here’s som of the code I’m using for parsing the dates and structuring the data:
struct StockDataPoint: Identifiable, Decodable {
var id: String { datetime }
let datetime: String
let close: String
var date: Date {
datetime.toDate() ?? Date()
}
var closePrice: Double {
Double(close) ?? 0.0
}
}
extension String {
func toDate() -> Date? {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = self.count == 10 ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm:ss"
return formatter.date(from: self)
}
}
And:
LineMark(
x: .value("Datum", point.date),
y: .value("Pris", point.closePrice)
)
.interpolationMethod(.cardinal)
.lineStyle(StrokeStyle(lineWidth: 0.7))
.foregroundStyle(.linearGradient(colors: [.blue, .yellow, .orange], startPoint: .bottomTrailing, endPoint: .topLeading))
.frame(height: 300)
.background(Color.black.opacity(0.6))
.chartYScale(
domain: (
(stockAPI.stockData.map { $0.closePrice }.min() ?? 0) * 0.98
...
(stockAPI.stockData.map { $0.closePrice }.max() ?? 100) * 1.02
)
)
.chartXAxis {
AxisMarks(values: .automatic(desiredCount: 5)) { value in
AxisGridLine().foregroundStyle(Color.gray.opacity(0.5))
AxisTick().foregroundStyle(Color.gray)
AxisValueLabel().foregroundStyle(Color.gray)
}
}
.chartYAxis {
AxisMarks(values: .automatic(desiredCount: 5)) { value in
AxisGridLine().foregroundStyle(Color.gray.opacity(0.5))
AxisTick().foregroundStyle(Color.gray)
AxisValueLabel().foregroundStyle(Color.gray)
}
}
What I need help with:
Skipping missing dates on the x-axis and show correct data for corresponding days.
Keeping the x-axis well formatted (grouped by month, accurate labels).
Thanks in advance for any suggestions!
There are hundreds of functions in my project that require creating shortcuts, but AppShortcutsProvider only supports up to 10 AppShortcut declarations, so I used over 100 AppIntents for users to manually add shortcuts (I did not add them to AppShortcutsProvider); The problem now is that I hope all the AppIntents I declare have specific names and function icons. I have tried my best to configure AppIntents with the query document, but the default display in the shortcut app is the icon of this application instead of the function icon I set. My code is as follows:
struct ResizeImageIntent: AppIntent {
static var title: LocalizedStringResource = "修改图片尺寸"
static var description: IntentDescription = IntentDescription("快速打开修改图片尺寸功能")
static var openAppWhenRun: Bool = true
func perform() async throws -> some IntentResult {
if let url = URL(string: "toolbox://resizeimage") {
await UIApplication.shared.open(url)
}
return .result()
}
}
The following is the code with icon configuration added:
struct VideoParseIntent: AppIntent {
static var title: LocalizedStringResource = "万能解析"
static var description: IntentDescription = IntentDescription("快速打开万能解析功能")
static var openAppWhenRun: Bool = true
// 修正:返回AppShortcut数组
static var appShortcuts: [AppShortcut] {
[
AppShortcut(
intent: VideoParseIntent(),
phrases: ["使用万能解析"],
systemImageName: "play.rectangle.on.rectangle" // 系统内置图标
)
]
}
func perform() async throws -> some IntentResult {
if let url = URL(string: "toolbox://videoparse") {
await UIApplication.shared.open(url)
}
return .result()
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi,
I want to follow the SwiftUI tutorials from Apple Developer. After creating the “Landmarks” app and clicking on ContentView, the preview shows:
Cannot preview in this file
Failed to launch net.bayerthomas.Landmarks
with the Diagnostics:
== PREVIEW UPDATE ERROR:
FailedToLaunchAppError: Failed to launch net.bayerthomas.Landmarks
==================================
| [Remote] JITError
|
| ==================================
|
| | [Remote] CouldNotLoadInputObjectFile: Could not load object file during preview: /Users/thomas/Library/Developer/Xcode/DerivedData/Landmarks-gpfsfizlhntsahandeumxmhwbjfj/Build/Intermediates.noindex/Landmarks.build/Debug-iphonesimulator/Landmarks.build/Objects-normal/arm64/ContentView.1.preview-thunk-launch.o
| |
| | path: /Users/thomas/Library/Developer/Xcode/DerivedData/Landmarks-gpfsfizlhntsahandeumxmhwbjfj/Build/Intermediates.noindex/Landmarks.build/Debug-iphonesimulator/Landmarks.build/Objects-normal/arm64/ContentView.1.preview-thunk-launch.o
| |
| | ==================================
| |
| | | [Remote] XOJITError
| | |
| | | XOJITError: '/Users/thomas/Library/Developer/Xcode/DerivedData/Landmarks-gpfsfizlhntsahandeumxmhwbjfj/Build/Intermediates.noindex/Landmarks.build/Debug-iphonesimulator/Landmarks.build/Objects-normal/arm64/ContentView.1.preview-thunk-launch.o': No such file or directory
I am on a fresh install of Xcode 16.3 on macOS 15.4.1.
Why is the official tutorial from Apple not working?
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello, im getting popping / crackling sounds from my Macbook Pro (M4 2024) speakers.
This happens when you do many certain tasks like click buttons or toggling switches when xcode has a simulator open and any background audio is playing, like spotify.
The speakers go crazy especially when starting the simulator in xcode with music in background.
Ive tried:
Using blackhole, and changing audio output in the simulator app
Deleting both .plist files form preferences file.
"coreaudiod" trick in terminal
restarting many times
different xcode versions and simulators and swift files
Nothing has worked. Any help?
In keyboard shortcuts this buttons at the bottom are overlappin.
Any one
else?
Topic:
UI Frameworks
SubTopic:
General
Using an App Clip link encoded into a QR Code shows an error when scanning the encoded QR Code on an iPhone or iPad.
After being scanned, the App Clip's banner is visible, but a message says: "App Clip Unavailable".
Accessing the same App Clip URL via Safari works as expected.
I've filed a feedback with more details and screenshots of the issue here: FB17891015
Thanks!
The swift syntax compilation reported an error.
as follows
How should I be compatible