Hi,
Is it possible to change font color of dark text in DatePicker in SwiftUI ? Also can we change size of arrows on top right ?
Kind Regards
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I am currently working on a comments section modeled after TikTok's/Instagram's comment sections for a media app. The view is a sheet view that is presented as follows:
.sheet(isPresented: $showChat) {
TakesChatView(viewModel: viewModel)
.presentationDetents([.medium, .large])
.presentationDragIndicator(.hidden)
.overlay(
VStack {
RoundedRectangle(cornerRadius: 2)
.fill(Color.gray)
.frame(width: 40, height: 5)
.padding(.top, 15)
.opacity(0.8)
Label("Chat", systemImage: "message.badge")
.lineLimit(nil)
.padding(.top, 5)
.padding([.leading, .trailing], 16)
Divider()
.padding(.top, 5)
.padding([.leading, .trailing], 16)
Spacer()
}
.frame(maxWidth: .infinity, alignment: .top)
)
}.ignoresSafeArea(.keyboard, edges: .bottom)
However, some issues arise regarding keyboard avoidance. Currently, when the user taps on the TextField to type a comment, the keyboard shifts the entire view upwards as it pops up. Instead, I need it where I can still view the comments without the keyboard affecting their placement when it pop up.
Below is the associated code for the comment view:
struct TakesChatView: View {
@ObservedObject var viewModel: TakeCommentViewModel
@FocusState var focus: Bool
@State private var selectedMedia: [PhotosPickerItem] = []
@State private var selectedImageData: [Data] = []
@State private var selectedGIFData: [Data] = []
@State private var selectedVideoData: [Data] = []
var textFieldNotEmpty: Bool {
!viewModel.textToPost.isEmpty ||
!selectedImageData.isEmpty ||
!selectedGIFData.isEmpty ||
!selectedVideoData.isEmpty
}
var body: some View {
GeometryReader { _ in
ZStack {
VStack {
contentView
commentTextField
.padding(.top,5)
}
}
}
.ignoresSafeArea(.keyboard, edges: .bottom)
.background(Color.containerBackground)
.onChange(of: viewModel.focus) { focus in
self.focus = focus
}
.onChange(of: selectedMedia) { _ in
loadMedia()
}
}
var contentView: some View {
VStack {
Spacer().frame(height: 105)
ScrollViewReader { scroll in
ScrollView(showsIndicators: true) {
ForEach(viewModel.comments, id: \.self) { comment in
TakeCommentView(
comment: comment,
viewModel: self.viewModel
)
.padding(.horizontal, 10)
.id(comment.documentID)
}
.onChange(of: viewModel.commentAdded) { id in
scroll.scrollTo(id, anchor: .bottom)
viewModel.commentAdded = nil
}
}
.scrollDismissesKeyboard(.immediately)
}
}
}
}
extension TakesChatView {
var commentTextField: some View {
VStack {
mediaPreview
HStack {
TextField("Type your comment", text: $viewModel.textToPost, axis: .vertical)
.keyboardType(.twitter)
.padding([.leading, .vertical], 6)
.focused($focus)
PhotosPicker(selection: $selectedMedia, matching: .any(of: [.images, .videos]), photoLibrary: .shared()) {
ComposeType.media.image
.frame(width: 40, height: 40, alignment: .center)
}
.onAppear {
selectedMedia.removeAll()
selectedImageData.removeAll()
selectedGIFData.removeAll()
selectedVideoData.removeAll()
}
postButton
}
.border(.lightGray, width: 1, cornerRadius: 10)
.padding([.bottom, .horizontal], 10)
}
}
}
I have tried using .ignoresSafeAres(), .safeAreaInset(), and custom keyboard observer functions but to no avail. How do I fix this issue?
Hi,
Some times long text damage the design of views it might go to a second row and increase view height and damage the overall design, so how to solve this issue, is there a way to set a Max Characters number for Text and TextField views in SwiftUI ? and maybe show few dots as used in some designs ?
Kind Regards
Error: 'Runningboard has returned error 5'
I am able to run my unit tests locally just fine. When I run them to from xcode cloud It fails everytime. I did notice in app store connect that it gives me a warning 'Grant access to the following repositories to allow them to be used for this product.' as I am using google sign in iOS(https://github.com/google/googlesignin-ios.git). However I cannot grant this access as I do not have privileges to google code base. I have imported the google sign in via swift package manager and everything works fine.
This is the report from xcode cloud if it helps. Happy to add any additional info that will help
Hi,
I'm currently working on some messages that should appear in front of the user depending on the system's state of my visionOS app. How am I able to change the distance of the appearing message relative to the user if the message is displayed as a View. Or is this only possible if I would create an enitity for that message, and then set apply .setPosition() and .relativeTo() e.g. the head anchor? Currently I can change the x and y coordinates of the view as it works within a 2D space, but as I'm intending to display that view in my immersive space, it would be cool if I can display my message a little bit further away in the user's UI, as it currently is a little bit to close in the user's view. If there is a solution without the use of entities I would prefer that one.
Thank you for your help!
Below an example:
Feedback.swift
import SwiftUI
struct Feedback: View {
let message: String
var body: some View {
VStack {
Text(message)
}
}
.position(x: 0, y: -850) // how to adapt distance/depth relative to user in UI?
}
}
ImmersiveView.swift
import SwiftUI
import RealityKit
struct ImmersiveView: View {
@State private var feedbackMessage = "Hello World"
public var body: some View {
VStack {}
.overlay(
Feedback(message: feedbackMessage)
)
RealityView { content in
let configuration = SpatialTrackingSession.Configuration(tracking: [.hand])
let spatialTrackingSession = SpatialTrackingSession.init()
_ = await spatialTrackingSession.run(configuration)
// Head
let headEntity = AnchorEntity(.head)
content.add(headEntity)
}
}
}
We are preparing a launch for iOS 18, and we experienced crashes from iOS 17 devices. If I load the app right from Xcode 16 RC to the iOS 17 device, then it works fine, but if I download it from TestFlight, the nit crashes.
The app crashes immediately upon launch due to a missing symbol in the Foundation framework. I'm hoping someone can provide insights or suggestions on how to resolve this.
Error Message
CopySymbol not found: _$s10Foundation14NSDecimalRoundyySpySo0B0aG_SPyADGSiSo14NSRoundingModeVtF
Referenced from: <C1ABDA48-29EE-3674-8554-669220A76F81> /Volumes/VOLUME/*/CamPlan.app/CamPlan
Expected in: <D92E19C1-6299-3E94-8614-C505D5ABCCDB> /System/Library/Frameworks/Foundation.framework/Foundation
What I've Tried
Verified that the app is compiled with the latest Xcode version
Checked for any usage of private APIs (none found)
Reviewed usage of Foundation framework methods, especially those related to NSDecimalRound
Questions
What could be causing this symbol to be missing?
Are there any known issues with NSDecimalRound or related functions in recent iOS versions?
How can I identify which part of my code is trying to use this missing symbol?
Topic:
App Store Distribution & Marketing
SubTopic:
TestFlight
Tags:
Foundation
iOS
SwiftUI
TestFlight
Hello,
I found that if you apply the new .sidebarAdaptable tab view style, the accessibility identifiers of tab bar buttons are missing.
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
Tab("Received", systemImage: "tray.and.arrow.down.fill") {
Text("Received")
}
.accessibilityIdentifier("tab.received") // 👀
Tab("Sent", systemImage: "tray.and.arrow.up.fill") {
Text("Sent")
}
.accessibilityIdentifier("tab.sent") // 👀
Tab("Account", systemImage: "person.crop.circle.fill") {
Text("Account")
}
.accessibilityIdentifier("tab.account") // 👀
}
.tabViewStyle(.sidebarAdaptable) // 👈 if remove this, ax identifiers are ok
}
}
#Preview {
ContentView()
}
The identifiers automatically appear after a few seconds. But this behaviour breaks a lot of the UI test cases.
When I copy and paste example code in apple developer documentation, LongPressGesture does not work as expected in Xcode Version 16.0 (16A242) and iOS 18. It seems updating(_:body:) method does not work when used with LongPressGesture.
When I make a breakpoint in updating(_:body:) method and long press the blue circle on the screen of simulator(or device), it is expected to be caught in breakpoint or it is expected that color of circle turns from blue to red to green. However, it is not caught in breakpoint and never turns to red.
Question of Stackoverflow is about same issue and I can not use onLongPressGesture method to implement required feature of my app.
Development environment: Xcode Version 16.0 (16A242), macOS 14.5
Run-time configuration: iOS 18.0
I am unable to use a framework that uses SwiftUI, built with the Xcode 16 release candidate, in Xcode 15.4. Attempting to build an app that uses the pre-built framework results in "Cannot find type 'SwiftUICore' in scope errors in the framework's private swift interface (.private.swiftinterface) file. For example
error: cannot find type 'SwiftUICore' in scope
@_Concurrency.MainActor @preconcurrency public var body: some SwiftUICore.View {
^~~~~~~~~~~
The problem is reproducible by creating a new framework project in Xcode 16, adding SwiftUI code to it, adjusting the deployment target, building the framework, then creating a new app project in Xcode 15.4, adding the framework to it, and attempting to build. In my test framework, I added the following type:
public struct BoldText: View {
let string: String
public init(_ string: String) {
self.string = string
}
public var body: some View {
Text(string).bold()
}
}
When I removed that type, a build of the framework with Xcode 16 became useable in Xcode 15.4.
Is this expected or is this a bug?
When I run a XCTest test on an IOS Target device, the test runs but the simulator is not opened so I can follow the screens being displayed and the key strokes. And when I initiate a record for a test method, it just hangs and never runs or open a simulator.
Is anyone else experiencing these same issues running XCTest?
Is this legacy framework not working with XCode 16 by design?
My app needs to send iMessages with an attached data file. The view comes up modally and the user needs to press the send button. When the button is tapped the error occurs and the attachment and message is not delivered.
I have tried three implementations of UIViewControllerRepresentable for MFMessageComposeViewController that have worked for iOS 15 and 16, but not 17. If I make the simplest app to show the problem, it will reliably fail on all iOS versions tested.
If I remove the attachment, the message gets sent. In contrast, the equivalent UIViewControllerRepresentable for email works perfectly every time. After struggling for weeks to get it to work, I am beginning to believe this is a timing error in iOS. I have even tried unsuccessfully to include dispatch queue delays.
Has anybody else written a swiftUI based app that can reliably attach a file to an iMessage send?
UIViewControllerRepresentable:
import SwiftUI
import MessageUI
import UniformTypeIdentifiers
struct AttachmentData: Codable {
var data:Data
var mimeType:UTType
var fileName:String
}
struct MessageView: UIViewControllerRepresentable {
@Environment(\.presentationMode) var presentation
@Binding var recipients:[String]
@Binding var body: String
@Binding var attachments:[AttachmentData]
@Binding var result: Result<MessageComposeResult, Error>?
func makeUIViewController(context: Context) -> MFMessageComposeViewController {
let vc = MFMessageComposeViewController()
print("canSendAttachments = \(MFMessageComposeViewController.canSendAttachments())")
vc.recipients = recipients
vc.body = body
vc.messageComposeDelegate = context.coordinator
for attachment in attachments {
vc.addAttachmentData(attachment.data, typeIdentifier: attachment.mimeType.identifier, filename: attachment.fileName)
}
return vc
}
func updateUIViewController(_ uiViewController: MFMessageComposeViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
return Coordinator(presentation: presentation, result: $result)
}
class Coordinator: NSObject, MFMessageComposeViewControllerDelegate {
@Binding var presentation: PresentationMode
@Binding var result: Result<MessageComposeResult, Error>?
init(presentation: Binding<PresentationMode>, result: Binding<Result<MessageComposeResult, Error>?>) {
_presentation = presentation
_result = result
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
defer {
$presentation.wrappedValue.dismiss()
}
switch result {
case .cancelled:
print("Message cancelled")
self.result = .success(result)
case .sent:
print("Message sent")
self.result = .success(result)
case .failed:
print("Failed to send")
self.result = .success(result)
@unknown default:
fatalError()
}
}
}
}
SwiftUI interface:
import SwiftUI
import MessageUI
struct ContentView: View {
@State private var isShowingMessages = false
@State private var recipients = ["4085551212"]
@State private var message = "Hello from California"
@State private var attachment = [AttachmentData(data: Data("it is not zip format, however iMessage won't allow the recipient to open it if extension is not a well-known extension, like .zip".utf8), mimeType: .zip, fileName: "test1.zip")]
@State var result: Result<MessageComposeResult, Error>? = nil
var body: some View {
VStack {
Button {
isShowingMessages.toggle()
} label: {
Text("Show Messages")
}
.sheet(isPresented: $isShowingMessages) {
MessageView(recipients: $recipients, body: $message, attachments: $attachment, result: $result)
}
.onChange(of: isShowingMessages) { newValue in
if !isShowingMessages {
switch result {
case .success(let type):
switch type {
case .cancelled:
print("canceled")
break
case .sent:
print("sent")
default:
break
}
default:
break
}
}
}
}
}
}
#Preview {
ContentView()
}
I have created a paging app With SwiftUI TabView with TabViewStyle: PageTabViewStyle. In every page there is an UICollectionView holding a list of rows. Now I have used UIViewControllerRepresentable to show the view inside TabView.
It works okay, but the Scroll to top gesture doesn't work here when pressed in the iPhones StatusBar.
Is it a fault of TabView or I am missing Something?
It may happen because of TabViews Scroll property. In UIKIT Views We needed to disable the scrollToTop property of scrollviews (Other then the desired one) is there any public API's for SwiftUI Views in replacement for setting scrollsToTop property?
Ok… I'm baffled here… this is very strange.
Here is a SwiftUI app:
import SwiftUI
@main struct StepperDemoApp: App {
func onIncrement() {
print(#function)
}
func onDecrement() {
print(#function)
}
var body: some Scene {
WindowGroup {
Stepper {
Text("Stepper")
} onIncrement: {
self.onIncrement()
} onDecrement: {
self.onDecrement()
}
}
}
}
When I run in the app in macOS (Xcode 16.0 (16A242) and macOS 14.6.1 (23G93)), I see some weird behavior from these buttons. My experiment is tapping + + + - - -. Here is what I see printed:
onIncrement()
onIncrement()
onIncrement()
onIncrement()
onDecrement()
What I expected was:
onIncrement()
onIncrement()
onIncrement()
onDecrement()
onDecrement()
onDecrement()
Why is an extra onIncrement being called? And why is one onDecrement dropping on the floor?
Deploying the app to iPhone Simulator does not repro this behavior (I see the six "correct" logs from iPhone Simulator).
When displaying a view with a Button inside a ScrollView using the sheet modifier, if you try to close the sheet by swiping and your finger is touching the Button, the touch is not canceled.
This issue occurs when building with Xcode 16 but does not occur when building with Xcode 15.
Here is screen cast.
https://drive.google.com/file/d/1GaOjggWxvjDY38My4JEl-URyik928iBT/view?usp=sharing
Code
struct ContentView: View {
@State var isModalPresented: Bool = false
var body: some View {
ScrollView {
Button {
debugPrint("Hello")
isModalPresented.toggle()
} label: {
Text("Hello")
.frame(height: 44)
}
Button {
debugPrint("World")
} label: {
Text("World")
.frame(height: 44)
}
Text("Hoge")
.frame(height: 44)
.contentShape(Rectangle())
.onTapGesture {
debugPrint("Hoge")
}
}
.sheet(isPresented: $isModalPresented) {
ContentView()
}
}
}
HoverEffectComponent on macOS 15 and iOS 18 works fine using RealityView, but seems to be ignored when ARView (even with a SwiftUI UIViewRepresentable) is used.
Feedback ID: FB15080805
When transferring files in a Multipeer Session, using the Progress instances (returned by either sendResource in the sender or the delegate method session(didStartReceiving:) on the receiver) in a SwiftUI ProgressView will eventually cause a crash (EXC_BAD_ACCESS in swift_retain on com.apple.MCSession.syncQueue)
I have created a small sample project that demonstrates the problem. It can be found at: https://github.com/eidria/Multipeer-Progress-Demo.git. A screen shot of the stack trace from a crash (crash.jpg) is in the “Images” folder.
STEPS TO REPRODUCE
Run the sample on two different hosts connected to the same network (project contains both iOS & macOS targets, bug manifests in any combination). When the second instance comes up, they will automatically find and connect to each other. When the “Send Files” button is enabled, clicking it will cause the sender to repeatedly send the file “Image.HEIC” from the “Images” folder to the receiver, which deletes it upon receipt of a successful transfer (i.e. delegate call back is called with a nil error). Subsequent transfers are triggered when the sender receives notice that the prior send completed successfully. Eventually, after some (usually small) number of files have been transferred, either the sender or receiver will crash in the middle of a transfer, with EXC_BAD_ACCESS in swift_retain on com.apple.MCSession.syncQueue.
Commenting out the ProgressView in the file FileTransferView.swift will allow the apps to run in perpetuity.
Hello. I am working with the iOS 18b8 and Xcode 16b6 betas, updating a Live Activity Widget to adopt the new FormatStyle variants of the SwiftUI Text views.
We used to use:
Text(workoutStartDate, style: .relative)
and it seems with iOS 18 we can replace it with:
Text(workoutStartDate, format: .relative(presentation: .numeric, unitsStyle: .wide))
The former code would auto-increment, allowing a user to look at their Live Activity and see the duration of their workout so far ticking by. The new code does provide a nice relative duration string, but it doesn't auto-increment in the Live Activity's View – I need that functionality.
I also updated other Texts in the Live Activity's View to adopt the .timer and .stopwatch FormatStyles. Those auto-increment and update no problem – once I realized I needed to provide a TimeDataSource<Date>.currentDate and not a simple Date.
But in this .relative case, there is no auto-incrementing, and I'm guessing it may be due to providing a Date (workoutStartDate) and not a TimeDataSource<Date> as TimeDataSource seems to be the magic to make the Text auto-increment (or it's possible this format simply doesn't support auto-increment? bummer if so since the prior way did).
How can I have a TimeDataSource<Date> that vends my arbitrary date (workoutStartDate)?
I dug around, didn't find anything, but I wouldn't be surprised if I was overlooking something.
PS: I have tried other approaches to solve this, such as simply using a .timer or .stopwatch format. That would change the under experience under iOS 18, and we think degrade it (the relative textual representation is nicer and provides distinction from the .timer also in the same View). We could keep the former approach, despite the minor layout issues under iOS 18. I have considered additional approaches as well – and am totally open to more! Here tho, I am truly curious how one might provide a custom TimeDataSource anchored at a date we provide (perhaps dynamically). Thank you.
The default design of TabView is 90% close to what I want. However, the icons, to my eye, lack a sufficient amount of spacing at the top, and slightly too much white space at the bottom.
Is there a way to give more top padding to the icons? To move the icons down without changing the height of the TabView itself?
Also, I find it weird that .labelStyle(.titleOnly) works on Tabs but .labelStyle(.iconOnly) doesn't work. Is that a bug? I had to use Image instead of Label:
TabView {
Tab {
MailView()
} label: {
Image(systemName: "envelope")
.padding(20)
}
Tab {
SettingsView()
} label: {
Image(systemName: "gearshape")
.padding(20)
}
}
code
import SwiftUI
@main
struct swiftuiTestApp: App {
@State private var value = "a";
var body: some Scene {
WindowGroup {
Menu("menu") {
Picker("", selection: $value) {
Text("A").tag("a")
Text("B").tag("b")
Text("C").tag("c")
}
.pickerStyle(.inline)
.onChange(of: value) { oldValue, newValue in
print("onChange", newValue)
}
}
}
}
}
on MacOS, onChange is not triggered when an option is selected for the first time, but subsequent option selections are triggered。
on MacOS, when Picker is not inside Menu, it works fine
on iOS, both works fine with inside or not inside menu
"Sign in with Apple" logo - how to make personalized for MacOS using my customized logo for the specific application?