struct DeployAndWithdrawDefensesAppIntent: WidgetConfigurationIntent {
// An example configurable parameter.
@Parameter(title:LocalizedStringResource("ax_alarm_device_name"))
}
In the process of using iOS widgetKit development team a, configuration item title need language internationalization (@ Parameter (title: LocalizedStringResource (" ax_alarm_device_name "))),
but found no effect. I first changed the language of the system on the iphone and found that the widget worked. However, just changing the language of the app did not take effect. Is there any way to just change the app language and make the widgets change? Thank you very much!
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 want to make my buttons inline with each other, but spaced apart, a bit like the apple topbar BUT in swift.
My code:
struct NormalPageView: View {
var body: some View {
VStack {
NavigationView {
Form {
Section {
Image(systemName: "house.fill")
Spacer()
Image(systemName: "plus")
Spacer()
Image(systemName: "gearshape.fill")
}
}
}
For whatever reason SwiftUI sheets don't seem to be resizable anymore.
The exact same code/project produces resizable Sheets in XCode 15.4 but unresizable ones with Swift included in Xcode 16 beta 2.
Tried explicitly providing .fixedSize(horizontal false, vertical: false) everywhere humanly possible hoping for a fix but sheets are still stuck at an awkward size (turns out be the minWidth/minHeight if I provide in .frame).
This crash occurs when the app is started, and it is not necessary. The probability of occurrence is relatively low and it is not easy to reproduce. Please guide me how to deal with it. Thank you
Please see the crash log below
Crash log
Making the call as:
UIApplication.shared.open(websiteURL)
doesn't open the browser and gives the following in the console:
BUG IN CLIENT OF UIKIT: The caller of UIApplication.openURL(:) needs to migrate to the non-deprecated UIApplication.open(:options:completionHandler:). Force returning false (NO).
However, making the call as:
UIApplication.shared.open(websiteURL) { _ in }
opens the browser and there is nothing in the cosole.
Does someone understand why is this or if it's Apple's iOS 18 bug? In the iOS & iPadOS 18 RC Release Notes | Apple Developer Documentation there is a section around resolving this or something similar, unsure.
Topic:
UI Frameworks
SubTopic:
UIKit
SwiftUI Buttons in a List no longer highlight when tapped. Seems to have stopped highlighting after iOS 16.0 I've only tested on an iPhone/simulators so not sure if iPad has the same issue.
The issue has been carried over to iOS 17 Beta 4. My app does not feel Apple like as there is no visual feedback for the user when a button in the list is pressed.
Does anyone know why this is occurring? Is this a bug on Apple's end?
I have a simple SwiftUI Text:
Text(t) .font(Font.system(size: 9))
Strangely its ideal height seems to be larger when it is empty.
I initially observed this in a custom Layout container that wasn't working quite right. Eventually I looked at the height returned by v.dimensions(in:), and found that when t is non-empty the height is 11; when empty, it's 14.
Subsequently I observed similar behaviour in a regular VStack container.
Has anyone seen anything similar? Are there any properties that could affect this behaviour?
(This is on a watch - I don't know if that matters.)
Hi,
Despite having CarPlay capabilities authorised for our navigation app, our users are seeing some odd behaviour in the appearance of the icon in the sidebar menu on the side of the CarPlay display.
The documentation suggests the quickbar will show the most recently used: navigation app,
Open our app in CarPlay
Switch to another non-navigation app via CarPlay sidebar
Note that our navigation app remains in sidebar
Switch back to our navigation app
Search for destination, select, tap 'Let's Go' to start navigation
Switch to a non-navigation app via CarPlay sidebar
Note that our app is replaced by another navigation app in the sidebar (Google/Apple), despite being the most recently used
Any ideas?
Not sure what could cause this. the UI align differently running on iPhone versus running on Mac. If I remove the HStack, it works but I still would like to know why, and if there is a way to make it right on both platforms.
Thank you
here is my code
@State private var viewModel = FirmwareSelectionViewModel()
var body: some View {
Form {
Section("Setup Name") {
TextField ( "", text: $viewModel.setupName )
.foregroundColor(.green )
.disableAutocorrection(true)
.onSubmit {
print ("On Submit")
}
}
Section("Battery") {
HStack() {
Text("Volt")
TextField("", value: $viewModel.Vnominal, format: .number)
.textFieldStyle(.roundedBorder)
.foregroundColor(.green )
#if !os(macOS)
.keyboardType(.decimalPad)
#endif
.onChange(of: viewModel.Vnominal) {
viewModel.checkEntryValidity()
print("Updated Vnominal: \(viewModel.Vnominal)")
}
Text("Ah")
TextField("", value: $viewModel.batteryCapacity, format: .number)
.textFieldStyle(.roundedBorder)
.foregroundColor(.green )
#if !os(macOS)
.keyboardType(.decimalPad)
#endif
.onChange(of: viewModel.batteryCapacity) {
viewModel.checkEntryValidity()
print("Updated Battery Capacity: \(viewModel.batteryCapacity)")
}
}
}
Section("Firmware Type") {
Picker(selection: $viewModel.selectedType, label: EmptyView()) {
ForEach(TypeOfFirmware.allCases) { type in
Text(type.rawValue).tag(type as TypeOfFirmware)
.foregroundColor(.green )
}
}
.pickerStyle(SegmentedPickerStyle())
Picker(selection: $viewModel.selectedFirmware, label: EmptyView()) {
ForEach(viewModel.availableFirmware) { firmware in
Text(firmware.rawValue.capitalized).tag(firmware as Firmware)
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
.onChange(of: viewModel.selectedType) {
viewModel.resetFirmwareSelection()
}
.navigationTitle("Firmware Selection")
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi,
I am having trouble setting default focus on a TextField that is inside of an alert. I expected TextField to receive default focus when alert is presented but result is that TextField does not receive default focus. This is happening on macOS 15.2, Swift (SwiftUI), Xcode 16.2 but hasn't worked on previous versions as well.
Example:
ContentView().alert("Sample Alert", isPresented: $present) {
AlertView()
} message: {
Text("Sample alert message.")
}
struct AlertView: View {
@Namespace private var namespace
@Environment(\.dismiss) private var dismiss
@State private var text = ""
var body: some View {
VStack {
TextField(text: $text, prompt: Text("Enter text")) {}
.onSubmit {
var _ = print(text)
dismiss()
}
.autocorrectionDisabled()
.lineLimit(1)
.prefersDefaultFocus(in: namespace)
Button("OK") {
dismiss()
}
Button("Cancel", role: .cancel) {
dismiss()
}
}
.focusScope(namespace)
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hi Apple developer,
I'm totally new in the development world using SwiftUI with just a little experience of Flutter.
Currently I'm struggling with the combination of VStack and the alignment of the sub views. I'm using a LazyVGrid with multiple Rectangles and overlays inside. The overlay contains a VStack with a leading alignment. And here is the problem. I framed them with a border to visualize the limits of these views. But it seams, that the leading alignment is not working properly. There is a large gap on the left side of the Image() and Text() views and I don't know why.
I'm very happy for any advice.
Here is my code of this view.
Thanks a lot!
import SwiftUI
import SwiftData
extension UIScreen {
static let screenWidth: CGFloat = UIScreen.main.bounds.size.width
static let screenHeight: CGFloat = UIScreen.main.bounds.size.height
static let screenSize: CGSize = UIScreen.main.bounds.size
}
struct TestView: View {
let constants: Constants = Constants()
let columnCount: Int = 2
let gridSpacing: CGFloat = 10
let gridRadius: CGFloat
let gridWidth: CGFloat
let gridHeight: CGFloat
let gridItems = [
Item(title: "Total", color: Color.gray, image: "dollarsign.circle.fill")
]
@State private var isSheetPresented: Bool = false
init() {
gridWidth = UIScreen._screenWidth / 2 - 3 * gridSpacing
gridHeight = 1.25 * gridWidth
gridRadius = gridWidth / 7.5
}
var body: some View {
NavigationStack {
ScrollView(.vertical) {
LazyVGrid(columns: Array(
repeating: .init(.flexible(), spacing: -2 * gridSpacing),
count: columnCount),
spacing: 2 * gridSpacing) {
ForEach(gridItems, id: \.title) { item in
RoundedRectangle(cornerRadius: gridRadius, style: .continuous)
.fill(item.color.gradient)
.frame(width: gridWidth, height: gridHeight)
.overlay(
VStack(alignment: .leading) {
Image(systemName: item.image)
.colorInvert()
.font(.system(size: 30))
.border(Color.yellow)
Spacer()
Text(item.title)
.font(.system(size: 20))
.foregroundColor(.white)
.border(Color.yellow)
}
.padding([.top, .bottom])
.frame(maxWidth: .infinity)
.border(Color.black)
)
}
}.padding(.top)
}
.navigationTitle("Test View")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Menu {
Button("Add", action: {})
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
}
}
}
struct Item: Identifiable {
let id: UUID = UUID()
let title: String
let color: Color
let image: String
}
#Preview {
TestView()
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hello,
I have a scroll view that when it appears I get a constant stream of warnings from the console:
CGBitmapContextInfoCreate: CGColorSpace which uses extended range requires floating point or CIF10 bitmap context
This happens whether or not I'm actively scrolling, so maybe it's not a scroll view issue at all? The reason I initially thought it was a scrollView issue was because when I scrolled the scrolling was no longer smooth, it was pretty choppy.
Also, I only get these warnings when I run my code on a real device - I do not get these on any simulators. Could it be the mesh gradient causing an issue?
I'm not sure what's causing the issue so I apologize in advance for what may be irrelevant code.
struct ModernStoryPicker: View {
@Environment(CategoryPickerViewModel.self) var categoryPickerViewModel
@EnvironmentObject var navigationPath: GrowNavigationState
@State private var hasPreselectedStory: Bool = false
@State private var storyGenerationType: StoryGenerationType = .arabicCompanion
var userInstructions: String {
if categoryPickerViewModel.userInputCategory.isEmpty {
"Select a category"
} else if categoryPickerViewModel.userInputSubCategory.isEmpty {
"Select a subcategory"
} else {
"Select a story"
}
}
var body: some View {
ZStack {
MeshGradient(width: 3, height: 3, points: [
[0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
[0.0, 0.5], [0.9, 0.3], [1.0, 0.5],
[0.0, 1.0], [0.5, 1.0], [1.0, 1.0]
], colors: [
.orange, .indigo, .orange,
.blue, .blue, .cyan,
.green, .indigo, .pink
])
.ignoresSafeArea()
VStack {
Picker("", selection: $storyGenerationType) {
ForEach(StoryGenerationType.allCases) { type in
Text(type.rawValue).tag(type)
}
}.pickerStyle(.segmented)
Text(userInstructions)
.textScale(.secondary)
automatedOrUserStories()
Spacer()
}.padding()
}
.onAppear {...}
}
@ViewBuilder func automatedOrUserStories() -> some View {
switch storyGenerationType {
case .userGenerated:
VStack {
Spacer()
Text("Coming soon!")
}
case .arabicCompanion:
VStack {
// TODO: Unnecessary passing of data, only the 2nd view really needs all these props
CategoryPickerView(
categories: categoryPickerViewModel.mainCategories(), isSubCategory: false,
selectionColor: .blue
)
CategoryPickerView(
categories: categoryPickerViewModel.subCategories(), isSubCategory: true,
selectionColor: .purple
)
ScrollView(.horizontal) {
HStack {
if categoryPickerViewModel.booksForCategories.isEmpty {
Text("More books coming soon!")
}
ForEach(categoryPickerViewModel.booksForCategories) { bookCover in
Button(action: {
// navigates to BookDetailView.swift
navigationPath.path.append(bookCover)
}) {
ModernStoryCardView(
loadedImage: categoryPickerViewModel.imageForBook(bookCover),
bookCover: bookCover
)
.scrollTransition(axis: .horizontal) { content, phase in
content
.scaleEffect(phase.isIdentity ? 1 : 0.5)
.opacity(phase.isIdentity ? 1 : 0.8)
}
}.buttonStyle(.plain)
}
}.scrollTargetLayout()
}
.contentMargins(80, for: .scrollContent)
.scrollTargetBehavior(.viewAligned)
}.padding()
}
}
}
struct CategoryPickerView: View {
@Environment(CategoryPickerViewModel.self) var viewModel
let categories: [String]
let isSubCategory: Bool
let selectionColor: Color
var body: some View {
ScrollView(.horizontal) {
HStack {
ForEach(categories, id: \.self) { category in
Button(action: {
withAnimation {
selectCategory(category)
}
}) {
TextRoundedRectangleView(text: category, color: effectiveColor(for: category))
.tag(category)
}.buttonStyle(.plain)
}
}
}.scrollIndicators(.hidden)
}
private func selectCategory(_ string: String) {
if !isSubCategory {
viewModel.userInputCategory = string
} else {
viewModel.userInputSubCategory = string
}
}
private func effectiveColor(for category: String) -> Color {
let chosenCategory = isSubCategory ? viewModel.userInputSubCategory : viewModel.userInputCategory
if category == chosenCategory {
return selectionColor
}
return .white
}
}
Working on a MacOS SwiftUI app - recently, when the app stays running from the night before, it no longer responds to keystrokes - data entry, or cursor navigation keys.
It does respond to mouse activity and clicks ... very weird.
I'm having the following issue:
Type 'AVPlayer.Type' cannot conform to 'ObservableObject'
struct MusicEditorView: View {
@ObservedObject var audioPlayer = AVPlayer
and this is the class:
class MusicPlayer: ObservableObject {
private var audioPlayer: AVPlayer?
private var timer: Timer?
func playSound(named sFileName: String){
if let url = Bundle.main.url(forResource: sFileName, withExtension: "mp3"){
audioPlayer = try? AVPlayer(url: url)
audioPlayer?.play()
}
}
func pause(){
audioPlayer?.pause()
}
func getcurrentProgress() -> Double{
guard let currentTime = audioPlayer?.currentItem?.currentTime().seconds else { return 0 }
guard let duration = audioPlayer?.currentItem?.duration.seconds else { return 0 }
return duration > 0 ? (currentTime / duration) * 100 : 0
}
func startProgressTimer(updateProgress: @escaping (Double, Double) -> Void){
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
guard let currentTime = self.audioPlayer?.currentItem?.currentTime().seconds else { return }
guard let duration = self.audioPlayer?.currentItem?.duration.seconds else { return }
updateProgress(currentTime, duration)
}
}
func stopProgressTimer(){
timer?.invalidate()
}
struct Sound: Identifiable, Codable {
var id = UUID()
var name: String
var fileName: String
}
}
}
Hi,
I detect dark mode on macOS like following:
NSAppearance *appearance = NSApp.mainWindow.effectiveAppearance;
NSString *interface_style = appearance.name;
NSAppearanceName basicAppearance = [appearance bestMatchFromAppearancesWithNames:@[
NSAppearanceNameAqua,
NSAppearanceNameDarkAqua
]];
if([basicAppearance isEqualToString:NSAppearanceNameDarkAqua]){
theme = "Adwaita:dark";
dark_mode = TRUE;
}
if([interface_style isEqualToString:NSAppearanceNameDarkAqua]){
theme = "Adwaita:dark";
dark_mode = TRUE;
}else if([interface_style isEqualToString:NSAppearanceNameVibrantDark]){
theme = "Adwaita:dark";
dark_mode = TRUE;
}else if([interface_style isEqualToString:NSAppearanceNameAccessibilityHighContrastAqua]){
theme = "HighContrast";
}else if([interface_style isEqualToString:NSAppearanceNameAccessibilityHighContrastDarkAqua]){
theme = "HighContrast:dark";
dark_mode = TRUE;
}else if([interface_style isEqualToString:NSAppearanceNameAccessibilityHighContrastVibrantDark]){
theme = "HighContrast:dark";
dark_mode = TRUE;
}
But this doesn't work if my window is in background. As the application window is put into background, it loses dark mode. Howto fix it?
regards, Joël
The stack trace is: Fatal Exception: NSInternalInconsistencyException Need an imageRef Have you encountered similar problems?
Topic:
UI Frameworks
SubTopic:
UIKit
We're encountering a UX challenge with the automatic App Store notification banner that appears when users first launch our App Clips (not the App Clip sheet). This notification, which suggests downloading the full app, is creating confusion among our users. We've observed that some users tap the notification instead of completing their intended action within the App Clip, interrupting their workflow.
Is there a way to disable this banner?
Hello,
I'm currently developing a CarPlay app using the CPTabBarTemplate, and I need to know if it's possible to disable user interaction with the tab bar, specifically preventing the user from switching between tabs or tapping on the tab items.
Is there a way to lock the selected tab or ignore tab switching attempts programmatically? I would like to maintain the tab bar UI but prevent users from changing tabs or interacting with it while in a certain mode or condition.
More specifically, if I have 2 pinned tabs that are displayed in different order for compact and regular and switch between compact and regular, when it gets to regular mode, the images for both tabs will not be rendered. The tabs can still be pressed, just the icon is missing.
Hi,,
How can I make a rectangle become taller as I swipe down on my trackpad?"
struct BlueRectangleView: View {
var body: some View {
VStack {
Rectangle()
.fill(Color.blue)
.frame(width: 200, height: 100)
.cornerRadius(10)
.shadow(radius: 5)
.padding()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.white)
}
}
struct BlueRectangleView_Previews: PreviewProvider {
static var previews: some View {
BlueRectangleView()
}
}