Hello,I'm using swiftUI to render my interface, the goal is to made a simple tableView. I'm using List, passing a param that is an array from an observableObject. The array isn't empty and each element is one identifiable that has an UUID. But, my application crashes when I try to show the list on the screen. The error:[TableView] Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc), and will also cause unnecessary performance overhead due to extra layout passes. Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the debugger and see what caused this to occur, so you can avoid this action altogether if possible, or defer it until the table view has been added to a window. Table view: <_TtC7SwiftUIP33_BFB370BA5F1BADDC9D83021565761A4925UpdateCoalescingTableView: 0x14409f000; baseClass = UITableView; frame = (0 0; 0 0); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x283e14f60>; layer = <CALayer: 0x2830b3fe0>; contentOffset: {0, 0}; contentSize: {0, 88}; adjustedContentInset: {0, 0, 0, 0}; dataSource: <_TtGC7SwiftUIP10$1f968ea4819ListCoreCoordinatorGVS_20SystemListDataSourceOs5Never_GOS_19SelectionManagerBoxS2___: 0x145160510>> *** Assertion failure in -[_TtC7SwiftUIP33_BFB370BA5F1BADDC9D83021565761A4925UpdateCoalescingTableView _Bug_Detected_In_Client_Of_UITableView_Invalid_Number_Of_Sections:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore/UIKit-3899.22.15/UITableView.m:2396The crash error message:** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (1 inserted, 0 deleted).'***The code:struct MyView: View {
@ObservedObject var filesArray = MyFiles()
var body: some View {
VStack {
MyFilesControllerWrapper(filesArray: filesArray)
List(filesArray.files) { (file: MyFile) in
NavigationLink(destination: MyDetailView(file: file) , label: { Text(file.filename ?? "") })
}
}
}
}The array class:class MyFiles: NSObject, ObservableObject {
@Published var files: [MyFile] = []
}The item code:class MyFile: NSObject, Identifiable, ObservableObject {
var id = UUID()
@Published var fileURL: URL
var filename: String?
...
}
How can create a new "Share View" ( now called "Share sheet" ? ) for iOS 13 ?In the new features of the iOS 13, we saw how the look (and possibly the way) with which we can share with other applications has changed.As I read in this article : iOS 13: The Ars Technica reviewI want to be able to display this menu with all the share options available in my SwiftUI app:So, even easier, how can I simply share a link - a text - to another App with Swift 5 using SwiftUI?What is the new way proposed ? What is the code that I have to write in my View to display this menu of options?Thank you.
Post not yet marked as solved
I have mac os 10.15 (19A583) in my Mac-Mini (Late 2014) and XCodeVersion 11.0 (11A420a)I have created simple Xcode projet using SwiftUI and I am not able to scroll the previewhttps://stackoverflow.com/questions/56704018/xcode-swiftui-how-to-scroll-the-preview-canvasAny help ?
Post not yet marked as solved
I have a GameView that has "@State var locationManager: LocationManager" which is passed to my MapView as a binding. The MapView conforms to UIViewRepresentable protocol. LocationManager conforms, among other things, to ObservableObject and has the following conformance-related code:var didChange = PassthroughSubject<locationmanager, never="">()
var lastKnownLocation: CLLocation {
didSet {
// Propagate the update to the observers.
didChange.send(self)
print("Finished propagating lastKnownLocation to the observers.")
} }I suppose that GameView and consequently MapView must be updated every time LocationManager.lastKnownLocation changes. In practice I only see MapView.updateUIView() called when I exit the app per home button. At this point control gets in updateUIView() and when I open the app again (not compile-install-run), I get the update. This also happens once short after the GameView() was presented.Is my understanding of how SwiftUI works wrong or is it some bug? How do I get it right?
How should my code be modified to ensure that when an exception happens at the Core Data layer when adding a new item, that SwiftUI does NOT continue to show a new item? Background: When I run the below code I get an exception when adding a new item doing the "context.save()", HOWEVER whilst the new item request really failed (did not save to Core Data), the UI does show a new item. It is as if the "lists" variable in the @FetchRequest line is not behaving dynamically. Question - How do I fix code so that the application works properly?Code: import SwiftUI
struct ContentView: View {
@Environment(\.managedObjectContext) var context
@FetchRequest(fetchRequest: List.allListFetchRequest()) var lists: FetchedResults
private func addListItem() {
let newList = List(context: context)
newList.id = 1
newList.title = "Testing 123"
do {
try context.save()
} catch let e as NSError {
print("Could not save new List. \(e.debugDescription)")
return
}
}
var body: some View {
NavigationView {
VStack {
ForEach(lists) { list in
Text("List = \(list.title)")
}
}
.navigationBarTitle( Text("My Todo Lists") )
.navigationBarItems(
trailing: Button(action: {self.addListItem()} ) {
Image(systemName: "plus.square")
}
)
}
}
}Example Output: Could not save new List. Error Domain=NSCocoaErrorDomain Code=133021 "(null)" UserInfo={NSExceptionOmitCallstacks=true, conflictList=(
"NSConstraintConflict (0x600001fcccc0) for constraint (\n id\n): database: (null), conflictedObjects: (\n \"0x600000a7e360 \",\n \"0xfb1bb528bb57810c \"\n)"
)}
I have a SwiftUI application in development, and for most screens, I'm fine with them being either landscape or portrait, and making designs for each orientation. However, for some screens, I would like to only allow the portrait orientation, and a few in only landscape. Essentially, something like the following StackOverflow post, but for SwiftUI:https://stackoverflow.com/questions/25606442/how-to-lock-portrait-orientation-for-only-main-view-using-swiftAnything like this for SwiftUI yet?
Post not yet marked as solved
This List in the first page of a tab view. When a cell is tapped, I want to show a new ChatRoomDetail view and hide tab bar. But I couldn't find a way in documentation. How should I do it? Thanks!struct ChatList: View { @State var showChatRoomDetail: Bool = false var items: [ChatRoom] var body: some View { NavigationView { List { ForEach(self.items) { item in NavigationLink(destination: ChatRoomDetail(currentMessage: "", chatRoom: item)){ Text(item.titleString) } } }
Post not yet marked as solved
My app is an master-detail map, all seems to be working ok but when I enter to the detail view, I go back to the master view, and then I try to go again to the same detail view. The second time the cell stay in a gray color and the app doesn't enter into the detail view.If you create a new master-detail project and you execute the template with no changes, you get the same bad behaviour.I'have tried with both xcode 11.2.1 and xcode 11.3 with no result.
I am trying to create a standard stepper with text field in swiftUI, but it does not seem to exist.I need something that looks like this:Do I have to create my own view, or is something already available?I tried an HStack with Text, TextField and stepper, but this does not align properly when placed in a form, and the stepper and text field cannot have a binding to the same value.Any ideas on how to implement this?
Hello,I'm having a blast learning SwiftUI but as a designer, and brand new developer, I'm really struggling with linking things and I don't quite have the vocabulary to follow Apple's documentation. With SwiftUI, I'd just love to have a button middle of the screen--I tap it and an AR Quick Look USDZ pops up.Could somebody point me in the right direction, connecting Quick Look to a button? And pretend like you're talking to a baby?https://developer.apple.com/documentation/arkit/previewing_a_model_with_ar_quick_lookThank you!-Dan
Post not yet marked as solved
This used to be possible to set the value for textColor key but I don't see how to do this within SwiftUI. Has anyone had any success with this or know how to set the appearance() global setting. Either works for me. -Kevin.
Post not yet marked as solved
How do you create a picker where the user's selection corresponds to different values of an enumerated type?
In SwiftUI, I have several TextFields in a Form and they always begin with initial caps when data is entered? How do I prevent this? I want the field to be all lowercase.
Aim:I have a model which is an ObservableObject. It has a Bool property, I would like to use this Bool property to initialise a @Binding variable.Questions:How to convert an @ObservableObject to a @Binding ?Is creating a @State the only way to initialise a @Binding ?Note:I do understand I can make use of @ObservedObject / @EnvironmentObject, and I see it's usefulness, but I am not sure a simple button needs to have access to the entire model.Or is my understanding incorrect ?Code:import SwiftUI
import Combine
import SwiftUI
import PlaygroundSupport
class Car : ObservableObject {
@Published var isReadyForSale = true
}
struct SaleButton : View {
@Binding var isOn : Bool
var body: some View {
Button(action: {
self.isOn.toggle()
}) {
Text(isOn ? "On" : "Off")
}
}
}
let car = Car()
//How to convert an ObservableObject to a Binding
//Is creating an ObservedObject or EnvironmentObject the only way to handle a Observable Object ?
let button = SaleButton(isOn: car.isReadyForSale) //Throws a compilation error and rightly so, but how to pass it as a Binding variable ?
PlaygroundPage.current.setLiveView(button)
Post marked as Apple Recommended
So currently what I have been doing for determining what device type and orientation I am in for SwiftUI is using sizeClasses, usually something like the following:struct SizeClassView: View {
@Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
var body: some View {
if horizontalSizeClass == .compact && verticalSizeClass == .regular {
Text("iPhone Portrait")
}
else if horizontalSizeClass == .regular && verticalSizeClass == .compact {
Text("iPhone Landscape")
}
else if horizontalSizeClass == .regular && verticalSizeClass == .regular {
Text("iPad Portrait/Landscape")
}
}
}What I'd like to know is: Is there any better way to do this in SwiftUI? The main problem I'm having with this method is that I can't differentiate between iPad Portrait and Landscape, but at least I can use it to differentiate between iPhone Portrait and iPhone Landscape and iPad... Any help and insight is greatly appreciated!
Post not yet marked as solved
Hi all!When presenting a specific modal sheet in a SwiftUI project, I consistently get a ton of console output like:=== AttributeGraph: cycle detected through attribute 290 ===Like, a couple hundred of these logs. It appears to be accompanied by a stutter/slowdown in the UI, but there's no crash and everything looks to be in the right place.Is the "cycle" here some sort of ARC retain cycle? Is it SwiftUI-specific? (I'm asking here because I've never seen this warning in a classic UIKit project.) Where can I go to learn more about this?Thanks!
On macOS we can add labels directly to SwiftUI slider. Has someone found a way how we can align two or more sliders in a VStack?- label text right aligned- all labels should have the same width (given by the largest text)- all slider bars should have the same but flexible width within the containers frame
Hi! I want to allow user to scroll a long list of items iOS app, so I am trying to embbed a List view in ScrollView view. However, the preview result doesn't work. Can you help me to check what I am missing?Below is my experimental code I entered to the file ContentView.swift, started with Single Page App project.struct ContentView: View {
var body: some View {
ScrollView{
List{
Text("abc")
Text("def")
}
.border(Color.yellow, width: 3)
.background(Color.blue)
}.padding(10).border(Color.red, width: 3)
}
}The preview of this code shows the red borders of the ScrollView, but not showing anything for the list, nor the text inside. If I change "List" to "VStack", then everything worked as expected.I don't understand why List doesn't work, and don't know how to fix it. Can you help me to find some clue?Thank you!
I'm surprised this simple code still doesn't work on iOS 13.3 / Xcode 11.3. On my iPhone SE it's almost all off screen.It's just two pieces of text, side by side, and two pickers, side by side. Anyone know a workaround? struct ContentView: View {
@State var choice: Int = 10
@State var choice2: Int = 10
var body: some View {
return VStack {
HStack {
Text("Some text here")
Spacer()
Text("Foo baz")
}
HStack {
Picker(selection: self.$choice, label: Text("C1")) {
ForEach(0..<10) { n in
Text("\(n) a").tag(n)
}
}
Picker(selection: self.$choice2, label: Text("C2")) {
ForEach(0..<10) { n in
Text("\(n) b").tag(n)
}
}
}
}
}
}
Post not yet marked as solved
Hi,I have TextField and a list with buttons NavigationLink.When i tap on NavigationLink i need to dismiss the keyboard, how?Thanks in advance.import SwiftUI
struct ContentView: View {
let array = ["John","Lena","Steve","Chris","Catalina"]
@State private var searchText = ""
var body: some View {
NavigationView{
List{
TextField("Type your search",text: $searchText)
.textFieldStyle(RoundedBorderTextFieldStyle())
ForEach(array.filter{$0.hasPrefix(searchText) || searchText == ""}, id:\.self){names in
NavigationLink(destination:keyboardDissmis(text: names)){
Text(names)
}
}
}
.navigationBarTitle(Text("Search"))
}
.gesture(DragGesture().onChanged{_ in UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)})
}
}
func keyboardDissmis(text:String)->Text{
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)
return Text(text)
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}