As far as I read about conditional Views this code should work. But it doesn't.
struct Consts {
static let myCondition = false //no difference if true or false
}
struct ContentView: View {
#State var toggle: Bool = false
var body: some View {
List() {
Text("Short Text is in first line")
Text("Second Line Text is a little longer but not much")
if Consts.myCondition {
Text("This is a conditional text. As in: when the user hasn't purchased the option he / she don't need a hint how to use this feature.")
// } else {
// Text("else doesn't help either.")
}
Toggle("I also have a toggle but it has nothing to do with this.", isOn: $toggle)
Text("Here we have a longer Text. Dont know what to type any more.")
Text("More text which is longer than a few lines.")
Text("Not so long Text")
}
.navigationTitle("Hints & Settings")
}
}
It compiles without warnings or errors. It loads up and displays fine, on simulator and on device. But every time I scroll the List upwards from the end, as soon as this if condition { Text() } should become visible the app crashes with
Fatal error: file SwiftUI, line 0
2021-03-07 06:36:26.548126+0100 WTFif WatchKit Extension[23163:641812] Fatal error: file SwiftUI, line 0
This is not limited to watchOS. It reproduces the same way in iOS, just the Texts have to be longer so that the if condition { Text() } becomes invisible when scrolling.
I have worked around the error with an array, conditional ranges and two ForEach() blocks.
struct ContentView: View {
let myHints = ["Short Text is in first line",
"Second Line Text is a little longer but not much",
"This is a conditional text. As in: when the user hasn't purchased the option he / she don't need to hint how to use this feature.",
"Here we have a longer Text. Dont know what to type any more.",
"More text which is longer than a few lines.",
"Not so long Text"]
var myUpperRange: ClosedRange<Int> {
if Consts.myCondition {
return 0...1
} else {
return 0...2
}
}
var myLowerRange: ClosedRange<Int> {
return 3...5
}
#State var toggle: Bool = false
var body: some View {
List() {
ForEach (myUpperRange, id: \.self) { i in
Text(myHints[i])
}
Toggle("I also have a toggle but it has nothing to do with this.", isOn: $toggle)
ForEach (myLowerRange, id: \.self) { i in
Text(myHints[i])
}
}
.navigationTitle("Hints & Settings")
}
}
My question basically is: am I not getting it or did I find a bug in Xcode / SwiftUI? Should my code above work? What could I have done different to make it work with the simple list of Texts?
Background: I also have a TabView with an if condition { MyTab() } which works without crashing. Do I have to worry that this might crash in the same way? Should I work around this as well before shipping?
PS: I am using Xcode 12.4 (12D4e)
Apparently this has been fixed by iOS 15 Beta 4: on my test device I had the error prior to the Beta 4 update, using a test app compiled with Xcode 13 Beta 3. After the update to iOS 15 Beta 4 the error is gone.
So I think it’s reasonable to say that the update to iOS 15 Beta 4 did fix the error.
Related
I am trying to create a LazyVGrid based on user selection in another view. As follows, the peoplelist and selectedpersonID are coming from other view.
I understand that I cannot use the "selectedpersons" during initializing of this view. I looked here(Cannot use instance member 'service' within property initializer; property initializers run before 'self' is available) to use onAppear() of the LazyVGrid.
It goes well during compiling and works ok if you select 1 person.
Once I selected 2 persons, I got a Fatal error that Index out of range at row.
struct Someview: View {
#ObservedObject var peoplelist : PersonList
let selectedpersonID : Set<UUID>?
#State private var days : [String] = Array(repeating: "0", count: selectedpersons.count * 5) //got first error here, during compiling
var body: some View {
VStack{
LazyVGrid(columns: columns) {
Text("")
ForEach(1..<6) { i in
Text("\(i)").bold()
}
ForEach(0..< selectedpersons.count , id: \.self) { row in
Text(selectedpersons[row].Name)
ForEach(0..<5) { col in
TextField("", text: $days[row * 5 + col])
}
}
}
.onAppear(){
days = Array(repeating: "0", count: selectedpersons.count * 5)}//no problem during compiling, but will have error when more than 1 person are selected.
.padding()
}
}
var selectedpersons: [Persons] {
return peoplelist.persons.filter {selectedpersonID!.contains($0.id)}
}
}
It seems to me that this OnAppear() is still slower than the content inside the LazyVGrid? So, the days is not changed quick enough for building the content insider the LazyVGrid?
Or did I make an error of the index in the array of days?
It's crashing because ForEach isn't a for loop its a View that needs to be supplied Identifiable data. If you're using indices, id: \self or data[index] then something has gone wrong. There are examples of how to use it correctly in the documentation.
Also onAppear is for performing a side-effect action when the UIView that SwiftUI manages appears, it isn't the correct place to set view data, the data should be already in the correct place when the View struct is init. Making custom Views is a good way to solve this.
Why running this code shows "Fatal error: Index out of range"?
import SwiftUI
struct MyData {
var numbers = [Int](repeating: 0, count: 5)
}
#main
struct TrySwiftApp: App {
#State var myData = MyData()
var body: some Scene {
WindowGroup {
ChildView(myData: myData)
.frame(width: 100, height: 100)
.onAppear {
myData.numbers.removeFirst() // change myData
}
}
}
}
struct ChildView: View {
let myData: MyData // a constant
var body: some View {
ForEach(myData.numbers.indices) {
Text("\(myData.numbers[$0])") // Thread 1: Fatal error: Index out of range
}
}
}
After checking other questions,
I know I can fix it by following ways
// fix 1: add id
ForEach(myData.numbers.indices, id: \.self) {
//...
}
or
// Edited:
//
// This is not a fix, see George's reply
//
// fix 2: make ChildView conforms to Equatable
struct ChildView: View, Equatable {
static func == (lhs: ChildView, rhs: ChildView) -> Bool {
rhs.myData.numbers == rhs.myData.numbers
}
...
My Questions:
How a constant value (defined by let) got out of sync?
What ForEach really did?
Let me give you a simple example to show you what happened:
struct ContentView: View {
#State private var lowerBound: Int = 0
var body: some View {
ForEach(lowerBound..<11) { index in
Text(String(describing: index))
}
Button("update") { lowerBound = 5 }.padding()
}
}
if you look at the upper code you would see that I am initializing a ForEach JUST with a Range like this: lowerBound..<11 which it means this 0..<11, when you do this you are telling SwiftUI, hey this is my range and it will not change! It is a constant Range! and SwiftUI says ok! if you are not going update upper or lower bound you can use ForEach without showing or given id! But if you see my code again! I am updating lowerBound of ForEach and with this action I am breaking my agreement about constant Range! So SwiftUI comes and tell us if you are going update my ForEach range in count or any thing then you have to use an id then you can update the given range! And the reason is because if we have 2 same item with same value, SwiftUI would have issue to know which one you say! with using an id we are solving the identification issue for SwiftUI! About id you can use it like this: id:\.self or like this id:\.customID if your struct conform to Hash-able protocol, or in last case you can stop using id if you confrom your struct to identifiable protocol! then ForEach would magically sink itself with that.
Now see the edited code, it will build and run because we solved the issue of identification:
struct ContentView: View {
#State private var lowerBound: Int = 0
var body: some View {
ForEach(lowerBound..<11, id:\.self) { index in
Text(String(describing: index))
}
Button("update") { lowerBound = 5 }.padding()
}
}
Things go wrong when you do myData.numbers.removeFirst(), because now myData.numbers.indices has changed and so the range in the ForEach showing Text causes problems.
You should see the following warning (at least I do in Xcode 13b5) hinting this could cause issues:
Non-constant range: not an integer range
The reason it is not constant is because MyData's numbers property is a var, not let, meaning it can change / not constant - and you do change this. However the warning only shows because you aren't directly using a range literal in the ForEach initializer, so it assumes it's not constant because it doesn't know.
As you say, you have some fixes. Solution 1 where you provide id: \.self works because now it uses a different initializer. Definition for the initializer you are using:
#available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Data == Range<Int>, ID == Int, Content : View {
/// Creates an instance that computes views on demand over a given constant
/// range.
///
/// The instance only reads the initial value of the provided `data` and
/// doesn't need to identify views across updates. To compute views on
/// demand over a dynamic range, use ``ForEach/init(_:id:content:)``.
///
/// - Parameters:
/// - data: A constant range.
/// - content: The view builder that creates views dynamically.
public init(_ data: Range<Int>, #ViewBuilder content: #escaping (Int) -> Content)
}
Stating:
The instance only reads the initial value of the provided data and doesn't need to identify views across updates. To compute views on demand over a dynamic range, use ForEach/init(_:id:content:).
So that's why your solution 1 worked. You switched to the initializer which didn't assume the data was constant and would never change.
Your solution 2 isn't really a "solution". It just doesn't update the view at all, because myData.numbers changes so early that it is always equal, so the view never updates. You can see the view still has 5 lines of Text, rather than 4.
If you still have issues with accessing the elements in this ForEach and get out-of-bounds errors, this answer may help.
OK before anymore marks this as duplicate, I have looked at posts similar to this on StackOverFlow and even the Apple forums, and implemented all recommended solutions, yet the problem persists. I've using a LazyVGrid. My code is as follows:
This is my custom scroll view that allows for pagination once the user reaches the end of the scroll:
if !quickSearchViewModel.isLoading && !quickSearchViewModel.search_result.isEmpty {
DataFetchingScrollView(.vertical, alignment: .center, onOffsetChange: { (off, height) in
offset = off
heightMinusOffset = height
if heightMinusOffset <= UIScreen.main.bounds.height &&
!quickSearchViewModel.search_result.isEmpty {
quickSearchViewModel.paginate_searchterm {
print("Paginated")
} onError: { (error) in
print(error)
}
}
}) {
createGrid()
.id(UUID())
}
And these are my two functions to create the grid and the view inside the grid:
private func createGrid() -> some View {
LazyVGrid(columns: columns) {
ForEach(quickSearchViewModel.search_result, id: \.product_uid) { product in
createProductItemView(product)
.id(product.product_uid)
}
}
}
private func createProductItemView(_ product: ProductModel) -> some View {
ProductItemView(product: product)
.id(product.product_uid)
}
Yes, I know I have spammed the id, but I've added '.id' to all views indivdually and the problem persists. It's as soon as I hit search, the content loads and appears in the grid and thats when my application crashes.
Edit - the product.product_uid is an auto-id generated by Firebase. I am literally using this same method in other views, and some work without issues, others may have a little bug.
Found this issue, it was because I was using orderBy when querying data.
[RESOLVED]
I am using a codable struct which stores the object values retrieved from an API call so I have amended my TextField using Cenk Belgin's example, I've also removed extra bits I've added in so if anyone else is trying to do the same thing then they won't have pieces of code from my app that aren't required.
TextField("Product Code", text: $item.ProdCode)
.onReceive(item.ProdCode.publisher.collect()) {
self.item.ProdCode = String($0.prefix(5))
}
Here is one way, not sure if it was mentioned in the other examples you gave:
#State var text = ""
var body: some View {
TextField("text", text: $text)
.onReceive(text.publisher.collect()) {
self.text = String($0.prefix(5))
}
}
The text.publisher will publish each character as it is typed. Collect them into an array and then just take the prefix.
From iOS 14 you can add onChange modifier to the TextField and use it like so :
TextField("Some Placeholder", text: self.$someValue)
.onChange(of: self.someValue, perform: { value in
if value.count > 10 {
self.someValue = String(value.prefix(10))
}
})
Works fine for me.
You can also do it in the Textfield binding directly:
TextField("Text", text: Binding(get: {item.ProCode}, set: {item.ProCode = $0.prefix(5).trimmingCharacters(in: .whitespacesAndNewlines)}))
I'm working through this SwiftUI tutorial here:
https://developer.apple.com/tutorials/swiftui/handling-user-input
And on Step 3 of the section "Adopt the Model Object in Your View", I get this error on the Toggle statement in line 16: "Generic parameter 'Label' could not be inferred."
My code is identical to that provided in the tutorial:
import SwiftUI
struct LandmarkList: View {
#EnvironmentObject var userData: UserData
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Favorites Only")
}
ForEach(userData.landmarkData) { landmark in
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
ForEach(["iPhone SE", "iPhone XS Max"], id: \.self) { deviceName in
LandmarkList()
.previewDevice(PreviewDevice(rawValue: deviceName))
.previewDisplayName(deviceName)
}
}
}
When I look at the code provided in the "Complete" folder, I see its nearly identical, except that the userData variable is made private—which I added to my "StartingPoint" version, though I can't imagine why it'd make a difference, and of course it still gives the same error and won't build. I can build and run the Complete version, so clearly the message about requiring a Generic parameter is wrong and it must have to do with something else like how the project is configured in settings.
I remember getting stuck earlier this summer with a similar issue in a different part of the tutorial, and found a post where someone explained why code would work in one project and not another, but I can't find that post now.
Is anyone familiar with this issue? Is there something else I need to understand about how to configure my project before I can reference an observable object in a toggle control in my view like this?
So as I mentioned in the comments: Just add .environmentObject(UserData()) under the ForEach() in your LandmarkList_Previews struct.
That would result in:
import SwiftUI
struct LandmarkList: View {
#EnvironmentObject var userData: UserData
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Favorites Only")
}
ForEach(userData.landmarkData) { landmark in
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationLink(destination: LandmarkDetail(landmark: landmark)
.environmentObject(self.userData)
) {
LandmarkRow(landmark: landmark)
}
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
ForEach(["iPhone SE", "iPhone XS Max"], id: \.self) { deviceName in
LandmarkList()
.previewDevice(PreviewDevice(rawValue: deviceName))
.previewDisplayName(deviceName)
}.environmentObject(UserData())
}
}
I had the exact same problem today and Ravi Mishra's comment resolved the issue for me (kudos to you). It must've been an autocomplete mistake.
ForEach(userData.landmarkData) should instead be ForEach(userData.landmarks)
I bothered my head about this tutorial for a week, went line by line through it twice by downloading the tutorial files again. I made sure that every character of my work in the tutorial matched every character of the completed project--twice--and still that nasty error message popped up as soon as I entered the final code. Stack Overflow was my last stop; when I read the solution was to include '.environmentObject(UserData())', I went right to my code to add it but it was already there!
Out of pure desperation, I decided to copy the (exact same) code for the body from the source of the completed project to the source in my tutorial project. The error disappeared.
I think #krjw has a point.