I have a simple List with nested children forming a tree. Each item can be checked. If all children are checked (or not) then the parent must reflect this state. It must also be possible to change the state of the children by selecting the parent.
Below is a simple example that sort-of works. When you change the state of a parent, the state of all the children change as well. But how do I make it work the other way around so that the parent is notified when a child changes? When all the children are checked, the parent should be checked.
I cannot get a reference to the parent. I tried adding handlers but that captures self (the parent) in an escaping closure that mutates it.
I created a timer for each item that would periodically check the children but this just feels very wrong.
I do not want to convert all the value-type coding to reference types but I cannot find an elegant way of solving this problem. Any suggestions will be greatly appreciated.
import SwiftUI
struct Item: Identifiable {
var id = UUID()
var name: String
var isSelected: Bool = false {
didSet {
guard children != nil else { return }
for i in 0..<children!.count {
children![i].isSelected = isSelected
}
}
}
var children: [Item]?
}
struct ContentView: View {
@Binding var itemsTree: [Item]
var body: some View {
List($itemsTree, children: \.children) { $item in
Toggle(item.name, isOn: $item.isSelected)
}
}
}
@main
struct ListQuestionApp: App {
@State private var itemTree: [Item] = [
Item(name: "Level 1", children: [
Item(name: "Level 2", children: [
Item(name: "Item B"),
Item(name: "Item A")
])
])
]
var body: some Scene {
WindowGroup {
ContentView(itemsTree: $itemTree)
}
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Crash Report
I have a sandboxed C++ console app that crashes before reaching main.
I can reproduce the problem by starting a new, empty console application. It crashes without any changes after I select it to be a sandbox app.
I have looked at this (Sandbox activated macOS application crashes immediately after execution) thread and this (Receiving this error 'EXC_BREAKPOINT') one but neither seem to be related, or give any clues.
My crash log (attached) mentions "Unable to get bundle identifier for container id". I've added a Info.plist but it made no difference.
What is causing this?
I feel a bit dumb asking for help because it is clear that git integration in XCode should just work, but it never worked for me and I hope someone can help.
I can see some more work went into XCode 15 Beta but it is not working well their either.
It always sort-of worked, but many features are just broken.
I can do basic commits and push to a remote but almost everything else is broken. The following basic things does not work:
Upstream changes are never shown. It shows that I am behind but there is nothing I can do about it.
Pull does not work. When I select "Pull" it shows "Loading..." in the dropdown. Pressing the Pull button dismisses the dialog, but does nothing. I have top pull from the command line, or use external app.
It does not show my current position in a repo correctly. Neither in my current branch, or when I look at the remotes (origin). Refresh and Fetch has no effect. I can switch to a different point in the branch, but the display does not show me that it happened. I can however confirm with command line or external tool that it worked (and obviously the code).
I did a very simple test where I made a local repo on the file system. I then cloned two projects from it, and used it to test the above. It works perfectly from command line, or Sourcetree, but not from XCode.
What am I doing wrong? I've read all the help from apple and various guides but clearly I am doing something wrong. It would have been nice if I did not have to switch my tools.
I would like to implement a global copy command for my app. The code below is an attempt at achieving this but does not work.
struct ContentView: View {
@State private var name = ""
var body: some View {
VStack {
Text("Hallo \(name)")
TextField("Please enter your name", text: $name)
}
.onCopyCommand(perform: {
print("You got to onCopy")
var items = [NSItemProvider]()
let stringData = "Hallo \(name)".data(using: .utf8)!
items.append(NSItemProvider(item: stringData as NSData, typeIdentifier: kUTTypePlainText as String))
return items
})
}
}
When the user selects something in the TextField, then using the copy menu should copy that text to the clipboard but when it has nothing selected, then I want to copy "Hallo" and the name to the clipboard.
As you can see, I tried using the onCopyCommand but Copy is always grayed out.
Any ideas on how I can enable Copy on the menu, and handle it when the TextField does not have anything selected?
I need to do a bit of customisation on a UITextView so I am creating a custom UIViewRepresentable to wrap the UITextView.
One of these is that the input should be centred and not wrap.
Searching on how to disable wrapping gives various conflicting recommendations, from not using UITextView to wrapping it in a UIScrollView. None of these seem to work reliably.
It seems like all that is required, is setting the size of the text container to be sufficiently wide but this is also not working. Below is what I've tried so far but it does not wrap the view.
The InputView also seems to take up the entire height of the screen. I have a feeling this is fundamentally part of my problem.
What am I missing?
import SwiftUI
struct InputView: UIViewRepresentable {
@Binding var text: String
typealias UIViewType = UITextView
func makeUIView(context: Context) -> UIViewType {
// Setup text view:
// ----------------
let textView = UITextView()
textView.textAlignment = .center
textView.delegate = context.coordinator
textView.font = UIFont.systemFont(ofSize: 72)
textView.textContainer.widthTracksTextView = false
textView.textContainer.size = CGSize(width: 20000, height: CGFloat.greatestFiniteMagnitude)
textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return textView
}
func makeCoordinator() -> InputView.Coordinator {
return Coordinator(self)
}
func updateUIView(_ textView: UIViewType, context: Context) {
if textView.text != text {
textView.text = text
}
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: InputView
init(_ parent: InputView) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
parent.text = textView.text
}
}
}
struct ContentView: View {
@State private var input: String = "ShouldNotWrapButScrollHorizontally"
var body: some View {
InputView(text: $input)
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Reading other questions and searching on the web, I am clearly missing something very obvious.
I am trying to make an app preview video for iOS. I've followed Creating Videos for App Previews to record a video on my iPhone 13. This gives me a video with a resolution of 2532 x 1170 (as expected).
The App preview specifications states that the native iPhone 13 resolution is 2436 x 1125 and that the accepted resolution is 1920 x 886.
Why is the app preview specification native resolution different from the actual iPhone 13 resolution? Am I missing some insets?
When I use Quick Time to save my video as 1080p then I get an output resolution of 1920 x 888 (it seems to be rounding up since the perfect scale would have been 1920 x 887,2037915).
I am unable to see how I can get to the accepted native resolution of 2436 x 1125 or how I can resample it to 1920 x 886.
I get the exact same results using the simulator.
How do I create a preview video in the accepted resolutions?
I've been trying to wrap a UITextField in UIViewRepresentable in order to do some customisation but this does not seem to work.
My main issue is that the frame of the UITextField is wrong. I even raised a TSI for this. It was confirmed to be a bug (I raised a bug report) but was told that the only work around is effectively to completely re-write my own Text Field using the basics. I cannot believe something as simple as this has not been solved yet.
Below is my minimum code to show the problem. I've tried a lot of things: adding InputView to a ScrollView; constraining the frame of InputView, etc. The problem is that when you keep on typing to fill the UITextField then it's frame gets a negative x-offset and it goes off the screen so that you can no longer see the cursor.
How do I fix this, or do I really have no choice but to re-write UITextField?
import SwiftUI
struct InputView: UIViewRepresentable {
let fontName = "Arial"
let fontSize: CGFloat = 32.0
@Binding var text: String
typealias UIViewType = UITextField
func makeUIView(context: Context) -> UIViewType {
// Setup text view:
// ----------------
let textView = UITextField()
textView.delegate = context.coordinator
// Creae a dummy view for the inputView (keyboard) so that the default
// keyboard is not shown:
let dummyView = UIView(frame: CGRect.zero)
textView.inputView = dummyView
return textView
}
func makeCoordinator() -> InputView.Coordinator {
return Coordinator(self)
}
func updateUIView(_ textView: UIViewType, context: Context) {
if textView.text != text {
textView.text = text
}
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: InputView
init(_ parent: InputView) {
self.parent = parent
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let currentValue = textField.text as NSString? {
let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
self.parent.text = proposedValue
}
return true
}
}
}
struct ContentView: View {
@State private var text: String = "Type here"
var body: some View {
VStack {
InputView(text: $text)
Text(text)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I am trying to implement a simple Table with a TextField that makes it possible to edit the data.
Below is a very simple example where I am trying to do this. It works, but it becomes very unresponsive as the number of people increases.
The example as it is, has 1,000 people. It is very slow when a TextField gets focus and is used to edit something. Strangely, it also gets very slow when you scroll through an entry that has been edited. It crashes completely when 10,000 people is used.
I found this similar question on the web, but it is not answered.
What should I do to implement an editable Table like this?
struct ContentView: View {
struct Person: Identifiable {
var givenName: String
var familyName: String
let id = UUID()
}
@State private var people = [Person].init(repeating: Person(givenName: "Name", familyName: "Family"), count: 1000)
var body: some View {
Table($people) {
TableColumn("Given Name") { $person in TextField("Name", text: $person.givenName) }
TableColumn("Family Name") { $person in TextField("Family Name", text: $person.familyName) }
TableColumn("Full Name") { $person in Text("\(person.givenName) \(person.familyName)")}
}
}
}
I have a simple app with a sidebar listing items and an edit view to edit the details of the selected item.
One of the parameters that can be changed in the edit view is the name of the item that is also shown in the sidebar.
Below is a simple app demonstrating the problem. It lits 4 people and you can change the name. When you change the name, the sidebar does not change until another is selected.
I would like the name in the sidebar to change as it is edited. If I added a text view in the edit view, then it would change as the TextField changes. Why does the item in the sidebar not change (or only change when selecting different item)?
class Person: NSObject, ObservableObject {
@Published public var name: String
init(name: String) {
self.name = name
}
}
class Database {
public var people: [Person]
init() {
people = [Person(name: "Susan"), Person(name: "John"),
Person(name: "Jack"), Person(name: "Mary")]
}
}
@main
struct BindingTestApp: App {
@State private var database = Database(
var body: some Scene {
WindowGroup {
ContentView(people: $database.people)
}
}
}
struct ContentView: View {
struct SidebarView: View {
@Binding var people: [Person]
@Binding var selectedPerson: Person?
var body: some View {
List(people, id: \.self, selection: $selectedPerson) { person in
Text(person.name)
}.listStyle(SidebarListStyle())
}
}
struct PersonView: View {
@ObservedObject public var person: Person
var body: some View {
TextField("Name", text: $person.name)
}
}
@Binding var people: [Person]
@State private var selectedPerson: Person?
var body: some View {
NavigationView {
SidebarView(people: $people, selectedPerson: $selectedPerson)
if let selectedPerson = selectedPerson {
PersonView(person: selectedPerson)
} else {
Text("Please select or create a person.")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
@State static private var database = Database()
static var previews: some View {
ContentView(people: $database.people)
}
}
We have a very large project that consists of 1000+ source files that builds 20+ targets (libraries and different versions of our app). Most is C++.
We recently started having problems with intenseness. The strange thing is that compiling and navigation works but simple code completion is suddenly very broken.
I manage to narrow it down to a simple use-case by deleting all the targets but one, and all the source files but two. I have a simple main.cpp that includes one header file test.h. If test.h is in the same folder as main.cpp, then intellisense works, but placing it in any other folder (all part of my project), intellisense stops working.
I've re-created this simple project from scratch, reproducing the file structure. Intellisense would work in this case. I could open the two projects side by side and went through all project and target settings and they were all identical, but the one from our original project does not work.
Can it be that the project contains something corrupt that was built up over the years? I really do not want to create the entire project and targets again from scratch.
I've done all the tricks I could find on the forums (Removing Derived folder; opening and closing Xcode; etc.). Nothing works, except apparently creating the project from scratch. The problem is also present in latest Xcode 15 Beta.
Any ideas on how to fix this?
I was hoping to use swift Mirror to create an extension that can change the properties of a struct.
It seems however that mutating the child items of the mirror is creating new instances and mutating those instead of the members of the method.
Below is a playground that shows my problem.
Can I use Mirror to achieve the goal of setting member values of structs that implement the given protocol, or should I take a different approach (and if so what)?
import Cocoa
struct Point {
var x: Int = 0
var y: Int = 0
}
protocol Shape {
var origin: Point { get }
}
extension Shape {
//: The hope is to have a generic function that will set the value of all parameters of type 'Point' but it is not working. The fact that I do not need "mutating" for this function is another clue that it will not mutate the members of the Shape.
mutating func clearAllPoints() {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
// It seems the line below creates a new point instance and it is not the same member of self.
if var point = child.value as? Point {
point.x = 0
point.y = 0
}
}
}
func printAllPoints() {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let point = child.value as? Point {
print("\(child.label!) = (x: \(point.x), y: \(point.y)")
}
}
}
}
struct Rectangle: Shape {
var origin = Point()
var corner = Point()
init() {
origin = Point(x: 10, y: 10)
corner = Point(x: 20, y: 30)
}
}
var rect = Rectangle()
//: rect has just been initialised, and the line below correctly prints all Points as initialised.
rect.printAllPoints()
//: Hope is that the line below will clear all Points but ...
rect.clearAllPoints()
//: ... it does not. The line below prints all Points with exactly the same values.
rect.printAllPoints()
I am doing text replacement in a SwiftUI TextField as the user types. This works fine when the cursor is at the end of the input, but fails when the user moves the cursor to the middle and start typing. As soon as a correction is made, the cursor jumps to the end of the string moving the user's cursor away from where they were editing.
Below is a simple example of a view doing text replacement. Is it possible to get the cursor position inside the onChange modifier, and preserve it without custom wrapping a UITextView. I've done that, and it creates other problems.
struct ContentView: View {
@State private var input: String = ""
var body: some View {
VStack {
TextField("", text: $input)
.onChange(of: input) {
input = input.replacingOccurrences(of: "*", with: "×")
input = input.replacingOccurrences(of: "/", with: "÷")
input = input.replacingOccurrences(of: "pi", with: "π")
}
}
.padding()
}
}
I am trying to get SwiftUI views to move from one position to another using animation. I know that when the identity of the views change this often result in a fade instead of an animation but I do not believe this is happening in my case.
Below is a simple example program with four views from a 2D array (the 2D array is important). There is a button to rotate the views clockwise.
I tried using two ForEach blocks but I cannot use it on the outer one because the row arrays does not conform to Identifiable. I also changed my code to write out the views explicitly without the ForEach blocks but I get the same result: The column changes animate as movement but the row changes animate as fades.
How do I get it to animate all four views moving clockwise?
import SwiftUI
struct Block: Identifiable {
var id : Int = 0
}
struct Board {
let numRows = 2
let numCols = 2
var blocks: [[Block]]
init() {
blocks = Array(repeating: Array(repeating: Block(), count: numCols), count: numRows)
for row in 0..<numRows {
for col in 0..<numCols {
blocks[row][col].id = row * numCols + col
}
}
}
mutating func rotate() {
let temp = blocks[0][0]
blocks[0][0] = blocks[1][0]
blocks[1][0] = blocks[1][1]
blocks[1][1] = blocks[0][1]
blocks[0][1] = temp
}
}
struct BlockView: View {
var block: Block
var body: some View {
ZStack {
Rectangle()
.fill(Color.secondary)
Text("\(block.id)")
.font(.largeTitle)
}
.aspectRatio(1.0, contentMode: .fit)
}
}
struct ContentView: View {
@State var board = Board()
var body: some View {
VStack {
Button("Rotate") {
withAnimation(.easeInOut(duration: 1.0)) {
board.rotate()
}
}
VStack {
ForEach(0..<2) { row in
HStack {
ForEach(board.blocks[row]) { block in
BlockView(block: block)
}
}
}
}
}
.padding()
}
}
#Preview {
ContentView()
}```