I'm making an app using SwiftUI and trying to use the TextEditor view. However when I run it, and I try entering text into the TextEditor, the characters don't appear, they do however appear in the terminal that i used to run the app. The same problem exists with the TextField view.
I usually run it using swift run but have also tried swift build and running the produced executable as well as using release mode.
Minimal example:
import SwiftUI
@main
struct Example: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State var text: String = ""
var body: some View {
TextEditor(text: $text)
}
}
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
I've encountered a weird issue with the new Map for iOS 17. In my list, which includes a MapView among other elements, I've observed that with the new initializer, the top and bottom bars are persistently displayed. They don't hide and only appear when scrolling, as they should. This problem doesn't occur with the old, now-deprecated initializer. To illustrate this, I have two screenshots: one with the map enabled and the other with the map disabled, demonstrating the issue.
Here is also my new Map code:
struct MapListRowView: View {
@Binding internal var location: LocationModel
@State internal var user: Bool = true
private var position: CLLocationCoordinate2D { .init(latitude: location.latitude, longitude: location.longitude) }
private var isPad: Bool { UIDevice.current.userInterfaceIdiom == .pad ? true : false }
var body: some View {
Map(bounds: .init(minimumDistance: 1250)) {
if user { UserAnnotation() }
Annotation("", coordinate: position) {
ZStack {
Circle().fill().foregroundColor(.white).padding(1)
Image(systemName: "mappin.circle.fill")
.resizable()
.foregroundColor(.indigo)
}.frame(width: 20, height: 20).opacity(user ? .zero : 1.0)
}
}
.frame(height: isPad ? 200 : 100)
.cornerRadius(8)
.listRowInsets(.init(top: -5, leading: .zero, bottom: -5, trailing: .zero))
.padding(.vertical, 5)
.disabled(true)
}
}
Dear Experts,
I have been looking at thr SimpleWatchConnectivity sample code:
https://developer.apple.com/documentation/watchconnectivity/transferring-data-with-watch-connectivity
There are a couple of things in there that look out of date. Firstly, it uses a WKApplicationDelegate to receive the background tasks. I believe this can probably be entirely removed, and replaced with .backgroundTask(.watchConnectivity) { ... } on the App. Is that true? What do I need something inside the { ... } there?
Secondly, it is using NSNotificationCenter to send received data from the WCSessionDelegate to the SwiftUI view hierarchy. Is there a better way to do that? I have spent a while trying to work out how a WCSessionDelegate class can connect to a binding to a SwiftUI @State property, and cause the UI to update in response to received data, but I haven't made it work.
Are there any newer examples of how to do this? I'm currently only trying to send some simple applicationContext state from the phone to the watch and have some views update to show the latest values.
Thanks, Phil.
Hi,
I am trying to read in which section in a list the user is currently located and want to scroll him to a specific section. Therefore I would like to use the new .scrollPosition modifier. Best would be the ability to implement the same snapping effect from ScrollView.
So I used this snippet:
struct Item: Identifiable{
var id: Int
static func getMany() -> [Item] {
var items = [Item]()
for i in 0..<100 {
items.append(Item(id: i))
}
return items
}
}
struct ContentView: View {
@State var items = Item.getMany()
@State var scrolledID: Item.ID?
var body: some View {
NavigationStack {
List {
ForEach(items) { item in
ItemView(item: item)
}
}
.scrollTargetLayout()
.scrollPosition(id: $scrolledID)
.navigationTitle("Hello, \(scrolledID ?? 0)")
}
}
}
struct ItemView: View {
var item: Item
var body: some View {
Text("Hello world, \(item)")
}
}
Doesn't work.
So I tried to place the modifiers in different places in the code to attack several different parts of the list as the "scrollTargetLayout" - but this doesn't change anything here.
Isn't the List View just the Form inside a ScrollView?! This doesn't work either. If I place the Form OR List inside a ScrollView, the contents of the list aren't displayed anymore. This seems logical, because the list is a LazyVStack rendering without a height, as it doesn't know its final height.
Can we fix this somehow?
I made a ImagePicker which worked pretty well. But when app get bigger it stops. Does not react to change isPresented value. As far I know I changed nothing around this part of an App. Also same thing happened in different place, another kind of picker.
print ("HELL'o") never prints. Silence.
struct ImagePicker: View {
@Binding var imageSource: ImageSource
@State var showFileImporter: Bool = false
@EnvironmentObject var manager: Manager
var body: some View {
VStack {
....
Button(action: {
print("before", showFileImporter)
showFileImporter = true
print("after", showFileImporter)
},
label: { Text("open Image") })
.buttonStyle(.borderless)
.controlSize(.mini)
}.fileImporter(isPresented: $showFileImporter,
allowedContentTypes: [.png, .jpeg, .tiff],
onCompletion: { result in
print ("HELL'o") // Never prints
switch result {
case let .success(url):
guard let _ = try? Data(contentsOf: url) else { return }
....
case let .failure(error):
print(error)
}
})
}
}
Does anybody have an idea what happened?
I suspect some settings in completely different palce or bug or computer does not like me.
Dear Experts,
I created a SwiftUI View (in a UIKit based project) whose objective is to display a short animation in the front of the user screen. I developed it 8 month ago in XCode 15 for iOS 17, no problems.
But since iOS 18, I can observe huge lags on my animation only in Release app. The problem is not present in Debug app.
I don't understand why this problem occurs, the animation is quite simple, it's just an offset deplacement.
I tried many thing like:
Show the animation with a UINavigationController
Show the animation with a UIWindow
Move the view with .position
Remove the GeometryReader
All other animation
withAnimation and .animation
Task and DispatchQueue
Etc...
I found that the laggy animation occurs when I set the Optimization Level for the Swift Compiler - Code Generation to Optimize for Speed [-O]. That's very strange because we had this option on Release for iOS 17 and we had no lags...
I can share to you a Sample Repository with the configuration we have. https://github.com/Thibma/sample-animation-swiftui
Today the only option I used is to develop this feature in UIKit but it's too bad to skip the SwiftUI opportunity. :/
If you have any ideas to resolve this, I take !
Thank you !
Hello, since the last version of iOS and WatchOS I have a problem with this code.
This is the minimal version of the code, it have two pickers inside a view of a WatchOS App.
The problem its with the focus, I can't change the focus from the first picker to the second one.
As I said before, it was working perfectly in WatchOS 10.0 but in 11 the problems started.
struct ParentView: View {
@FocusState private var focusedField: String?
var body: some View {
VStack {
ChildView1(focusedField: $focusedField)
ChildView2(focusedField: $focusedField)
}
}
}
struct ChildView1: View {
@FocusState.Binding var focusedField: String?
@State private var selectedValue: Int = 0
var body: some View {
Picker("First Picker", selection: $selectedValue) {
ForEach(0..<5) { index in
Text("Option \(index)").tag("child\(index)")
}
}.pickerStyle(WheelPickerStyle()).focused($focusedField, equals: "first")
}
}
struct ChildView2: View {
@FocusState.Binding var focusedField: String?
@State private var selectedValue: Int = 0
var body: some View {
Picker("Second Picker", selection: $selectedValue) {
ForEach(0..<5) { index in
Text("Option \(index)").tag("childTwo\(index)")
}
}.pickerStyle(WheelPickerStyle()).focused($focusedField, equals: "second")
}
}
When you do vertical scrolling on the second picker, the focus should be on it, but it dosnt anything.
I try even do manually, setting the focusState to the second one, but it sets itself to nil.
I hope that you can help me, thanks!
Hello, I have been implementing faceID authentication using LocalAuthentication, and I've noticed that if i use swift 5 this code compiles but when i change to swift 6 it gives me a crash saying this compile error:
i have just created this project for this error purpose so this is my codebase:
import LocalAuthentication
import SwiftUI
struct ContentView: View {
@State private var isSuccess: Bool = false
var body: some View {
VStack {
if isSuccess {
Text("Succed")
} else {
Text("not succeed")
}
}
.onAppear(perform: authenticate)
}
func authenticate() {
let context = LAContext()
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "We need to your face to open the app"
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { sucexd, error in
if sucexd {
let success = sucexd
Task { @MainActor [success] in
isSuccess = success
}
} else {
print(error?.localizedDescription as Any)
}
}
} else {
print(error as Any)
}
}
}
#Preview {
ContentView()
}
also i have tried to not use the task block and also gives me the same error. i think could be something about the LAContext NSObject that is not yet adapted for swift 6 concurrency?
also i tried to set to minimal but is the same error
Im using xcode 16.1 (16B40) with M1 using MacOS Seqouia 15.0.1
Help.
Noticed in iOS 18 that List element with animation modifier behaves differently. Seems that on first change of the underlying State property List updates all elements and loses its scroll position even if you insert just one element.
The following code reproduces the behaviour, if you run it on iOS 17 it will behave as expected, you'll see an element being added to the list with an acompanying animation. On iOS 18 you'll lose your scroll position and judging by the animation it seems to update all the other rows in the list even though only one element of the underlaying State property was inserted. After that first update, list element on iOS will behave as expected.
To reproduce the issue scroll down to the ~50th element and tap on a row, compare the behaviour on iOS 17 and iOS 18.
import SwiftUI
struct ContentView: View {
struct ViewState: Equatable {
struct Value: Identifiable, Equatable {
let id: String
var text: String
var value: Bool
}
let list: [Value]
}
@State var viewState: [ViewState.Value] = {
return (0..<100).map { id in
ViewState.Value(
id: "\(id)",
text: "Row number: \(id + 1)",
value: Bool.random()
)
}}()
var body: some View {
list(viewState)
}
@ViewBuilder
private func list(_ list: [ViewState.Value]) -> some View {
List {
ForEach(list) { row in
self.value(row)
}
}
.animation(.default, value: viewState)
}
@ViewBuilder
private func value(_ value: ViewState.Value) -> some View {
Button(action: {
guard let rowIndex = viewState.firstIndex(where: { $0.id == value.id }) else {
return
}
viewState.insert(randomValue(id: rowIndex), at: rowIndex + 1)
}) {
VStack {
Text(value.text)
Text("\(value.value ? "ON" : "OFF")")
.foregroundStyle(value.value ? Color.green : Color.red)
}
}
}
private func randomValue(id: Int) -> ContentView.ViewState.Value {
let id = (id*100 + 1)
return .init(id: "New id: \(id)", text: "Row number: \(id)", value: Bool.random())
}
}
Issues has already been reported using feedback assistant FB16082730
Hello
I want to be able to save Date in @AppStorage, and it works however I was wondering what was the difference between these two extensions, which one is better and why?
extension Date: RawRepresentable {
static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()
public var rawValue: String {
Date.dateFormatter.string(from: self)
}
public init?(rawValue: String) {
self = Date.dateFormatter.date(from: rawValue) ?? Date()
}
}
and
extension Date: RawRepresentable {
private static let formatter = ISO8601DateFormatter()
public var rawValue: String {
Date.formatter.string(from: self)
}
public init?(rawValue: String) {
self = Date.formatter.date(from: rawValue) ?? Date()
}
}
Thank You!
Is there any way to get dock size?
I got Dock Window using CGWindowListCopyWindowInfo.
But I found its frame covers my entire screen.
Same promble as Notification Center.
Any way to get their size?
I use the effect in the picture to do the test, I want to achieve a habit of multiple punch card effect, click to complete a punch card, long press to cancel a punch card.
I'm having a problem right now. I want the long press gesture to only work on the trash icon, not extend to the entire item, causing the entire item to be highlighted.
What should I do about it? I tried a lot of methods, but I didn't achieve the effect.
I'm building a SwiftUI+RealityKit app for visionOS, macOS and iOS. The main UI is a diorama-like 3D scene which is shown in orthographic projection on macOS and as a regular volume on visionOS, with some SwiftUI buttons, labels and controls above and below the RealityView.
Now I want to add UI that is positioned relative to some 3D elements in the RealityView, such as a billboarded name label over characters with a "show details" button and such.
However, it seems the whole RealityView Attachments API is visionOS only? The types don't even exist on macOS. Why is it visionOS only? And how would I overlay SwiftUI elements over a RealityView using SwiftUI code on macOS if not with attachments?
Hi! We added Spanish to the String Catalog. Turned out there are a lot of changes we should make to already localized text. How can we temporarily turn off / disable this language to fix all issues and then turn on Spanish support again?
Thank you!
Hi all,
Very new to this. Just getting into swift data, and am frustrated with the canvas not working with modelContainers in SwiftData. My understanding is that they work if inMemory = true, but not in the default case where data is persistent after an app is quit.
Can anyone tell me if it is possible to conditionally create the modelContainer type based on a flag... If Bool:Canvas then inMemory = True, Else False... Then using this flag for all data models so my list views populate on the canvas, without having to run the simulator each time... I would assume you could also pre-populate the inMemory option if it is empty also...
Or is there a simple and obvious solution that I am oblivious to.
If it is possible, is it worth the time, hassle, and any possible issues?
crash log
Anyone can understand the log? I really don't understand.
Please see the attachment crash and help to resolve it, thanks very much.
Hi,
When closing a WindowGroup, I want to show a prompt, and only dismiss the window when the user confirms.
How to do it?
WindowGroup(id: "A") {
ContentView()
}
Hi everyone,
I’m having trouble getting the correct horizontal slide transitions when navigating between multiple screens in my SwiftUI app. I have three screens (enum cases with an int assigned as index depending on the navigation order): .checkClient (index 0), .login(document: String) (index 1), and .register (index 2).
My goal is:
When moving forward (e.g., from .checkClient to .login, or from .login to any other with a greater index), the new screen should enter from the right (trailing) and the old one should exit to the left (leading).
When going backward (from .register back to .checkClient, for example), the new screen should enter from the left (leading) and the old one should exit to the right (trailing).
I’ve been using a state property isAdvancing to determine the direction of transitions (I use TCA, so my logic is in a Reducer body, my properties in a State and my views are normal SwiftUI Views):
case .updateCurrentScreen(let newScreen):
state.isAdvancing = newScreen.index > state.currentScreen.index
state.currentScreen = newScreen
return .none
I tried applying .transition directly inside each case:
.transition(
.asymmetric(
insertion: .move(edge: store.isAdvancing ? .trailing : .leading),
removal: .move(edge: store.isAdvancing ? .leading : .trailing)
)
)
This works correctly the first time I navigate forward. However, when I go to the .register screen and then hit back, the directions become inconsistent. Sometimes the removal happens in the wrong direction, and after returning to .checkClient, forward navigations stop working as intended.
Then, I tried placing the transition at a higher level, wrapping the switch in a ZStack and using a single .transition(...) outside:
ZStack {
switch store.currentScreen {
case .checkClient:
StartView(...)
case .login:
LoginView(...)
case .register:
RegisterView(...)
}
}
.transition(
.asymmetric(
insertion: .move(edge: store.isAdvancing ? .trailing : .leading),
removal: .move(edge: store.isAdvancing ? .leading : .trailing)
)
)
.animation(.easeInOut, value: store.currentScreen)
But doing this results in some transitions reverting to a fade instead of a horizontal slide.
I’ve also tried ensuring that isAdvancing updates before changing the currentScreen. Unfortunately, I still encounter inconsistent transitions when navigating back and forth between these screens.
Here is my complete view logic (even though is not finished nor polished yet):
var body: some View {
WithPerceptionTracking {
ZStack {
AdaptiveSheetView(
backgroundImage: Asset.AuthorizationDomain.background,
hasBackButton: store.showsBackButton,
isFullScreen: store.isFullScreen,
backAction: {
store.send(.goBack)
}
) {
if store.showsIATILogo {
Image(asset: Asset.iatiLogo)
.padding(spacing: .medium)
}
ZStack {
switch store.currentScreen {
case .checkClient:
StartView(store: store.scope(state: \.startState, action: \.startAction))
case .login:
if let newStore = store.scope(state: \.loginState, action: \.loginAction) {
LoginView(store: newStore)
}
case .register:
if let newStore = store.scope(state: \.registerState, action: \.registerAction) {
RegisterView(store: newStore)
}
}
}
.transition(
.asymmetric(
insertion: .move(edge: store.isAdvancing ? .trailing : .leading),
removal: .move(edge: store.isAdvancing ? .leading : .trailing)
)
)
}
.animation(.easeInOut, value: store.currentScreen)
if store.startState.checkUser == .loading { LoadingSpinner() }
PreloadView(store: store.scope(state: \.preloadState, action: \.preloadAction))
.opacity(store.preloadViewShown ? 1.0 : 0.0)
.animation(.linear(duration: 0.5), value: store.preloadViewShown)
.onChange(of: store.preloadViewShown) { shown in
if !shown { store.send(._checkPreviousSessions) }
}
}
}
}
Has anyone experienced similar issues or found a reliable pattern for achieving these “push/pop” style transitions in SwiftUI? Any guidance would be greatly appreciated!
My minimum target is iOS 16, so I can not make use of TabView with paginated style for this AFAIK.
Thanks in advance for any time and attention you dedicate to me 🙏🏼
Hey I wanted to see what this mean (Thread 1: SwiftUI Body (1)). It pops up every time I run my app. When it comes to the navigation view and typing in a login. The app freezes and, stops the animation. Does anyone know how to fix this?
Hello. I’ve encountered a strange issue with TimelineView and wanted to report it.
The following code runs without any problems:
// Example 1.
struct ContentView: View {
var body: some View {
TimelineView(.everyMinute) { _ in
List {
TimelineView(.everyMinute) { _ in
Text("Hello")
}
}
}
}
}
However, the code below causes the CPU usage to spike to 100%, and the screen displays a blank view:
// Example 2.
struct ContentView: View {
var body: some View {
TimelineView(.everyMinute) { _ in
List {
TimelineView(.everyMinute) { _ in
text
}
}
}
}
var text: some View {
Text("Hello")
}
}
The same issue occurs with the following code:
// Example 3.
struct MyTextView: View {
var body: some View {
Text("Hello")
}
}
struct ContentView: View {
var body: some View {
TimelineView(.everyMinute) { _ in
List {
TimelineView(.everyMinute) { _ in
MyTextView()
}
}
}
}
}
Replacing List with LazyVStack and ForEach resolves the hang issue, but I need to use List because I rely on the swipeActions().
Does anyone have insights or suggestions on how to address this issue?