Posts

Post not yet marked as solved
1 Replies
230 Views
Hello everyone, I'm facing a problem that I can't connect the button to the unwind segue. I have made a simple application with three controllers. The unwind segue code is located in Table View Controller. @IBAction func unwindToTableViewController(_ unwindSegue: UIStoryboardSegue) { let sourceViewController = unwindSegue.source } A first segue has been implemented from the Add button on Table View Controller to the View controller. It is a Push type. There is a Save button as Bar Button Item in the View Controller. When I try to drag a connection from Save button to the Exit icon of the View Controller, the context menu does not open indicating the unwind segue. Instead, a context menu appears with different types of segues. At the same time, if I just click the Exit icon, a context menu appears where the unwind method is visible. Just in case, I re-read the documentation again and looked at examples of using the unwind method. There is no mention of this problem anywhere. The only hypothesis left is that this problem is related to the new version of Xcode. The example of application given here was created in XCode 15.3. I have tested the same application on another computer, where the version of Xcode is 13.4.1. There, when I try to drag a connection from the Save button to the Exit icon, a context menu appears with the name of the unwind method. But the problem didn't end there because after the connection is established, the button does not work and the View Controller does not dismiss. I can't understand why this is happens. It worked before. Is that one a bug or the feature? How to fix it? Any ideas would be greatly appreciated!
Posted
by John368.
Last updated
.
Post not yet marked as solved
7 Replies
2.6k Views
Hi everyone, I'm trying to follow the Landmarks project tutorial and got stuck in the second part, in the second section (Create the Row View), step 6 where it says "Modify the text view to use the landmark property’s name." This must be done in the LandmarkRow.swift file. https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation The tutorial shows that after doing this, the preview will display the name of the landmark (Turtle Rock) instead of the usual "Hello world" greeting. But my replacement is not happening. Moreover, from this point on, the preview stops working. There are no error messages in the code, except for the message that the preview could not be performed. I checked and rewrote the code several times, replaced the data source files, but nothing helped. At the same time, the preview works well in other view files. I can't figure out what's wrong with my code? Any ideas as to what the reason will be is appreciated. Below is the code of two files, the LandmarkRow.swift, where view does not work, the second is ModelData.swift and it is related to the previous one. LandmarkRow.swift import SwiftUI struct LandmarkRow: View {     var landmark: Landmark     var body: some View {         HStack {             landmark.image                 .resizable()                 .frame(width: 50, height: 50)             Text(landmark.name)             Spacer()         }     } } struct LandmarkRow_Previews: PreviewProvider {     static var previews: some View {         LandmarkRow(landmark: landmarks[0])     } } ModelData.swift import Foundation var landmarks: [Landmark] = load("landmarkData.json") func loadT: Decodable(_ filename: String) - T {     let data: Data     guard let file = Bundle.main.url(forResource: filename, withExtension: nil)     else {         fatalError("Couldn't find \(filename) in main bundle")     }     do {         data = try Data(contentsOf: file)     } catch {         fatalError("Couldn't load \(filename) from main bundle:\n\(error)")     }     do {         let decoder = JSONDecoder()         return try decoder.decode(T.self, from: data)     } catch {         fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")     } }
Posted
by John368.
Last updated
.
Post marked as solved
13 Replies
6.0k Views
Hi everyone,I try to pass data from View Controller through Tab Bar Controller and Navigation Controller to Table View Controller. Screenshot of storyboard is bellow.https://drive.google.com/open?id=1GW6gaDxfK1zaEOk2aPE8izkS5B67ldZLMy code is next:1. Send data from View Controller@IBAction func addToCarButton(_ sender: UIButton) { tabBarController?.selectedIndex = 1 let navVC = tabBarController?.viewControllers![1] as! UINavigationController// let cartTableViewController = navVC.topViewController as! CartTableViewController cartTableViewController.titleItem = titleLabel.text cartTableViewController.image = SomeImage(photo: imageView.image!) }2. Get data in Table View Controllerimport UIKit class CartTableViewController: UITableViewController { // MARK: - Store data // Create variables for receiving data (title and data from image) from VC var titleItem: String? var image: SomeImage? // Create shopping cart - array of selected items var cartItems = [Cart]() var cartItem: Cart? override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { //Load data from archive file cartItems = Cart.loadFromFile() // Create a new item if titleItem != nil, image != nil { print("titleItem in Cart View Appear - \(String(describing: titleItem))") cartItem = Cart(title: titleItem!, image: image!) } // Add new item to shopping cart if cartItem != nil { cartItems.append(cartItem!) } tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cartItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath) // Pass title to cell cell.textLabel?.text = cartItems[indexPath.row].title // Retrieve image from array of archive file and convert from Data to UIImage format let image = UIImage(data: cartItems[indexPath.row].image.photo) // Pass image to cell: cell.imageView?.image = image return cell } // MARK: - Save data to archieve file override func viewWillDisappear(_ animated: Bool) { Cart.saveToFile(cartItems: cartItems) tableView.reloadData() } // Clear cart @IBAction func clearCartButton(_ sender: UIBarButtonItem) { cartItems.removeAll() tableView.reloadData() }But data are appear only after second click. I.e., I add item 1 and cart is empty. When I add item 2, cart has item 1. If then I add item 3, card has item 1 and item 2, and go on.I have done link bellow on gif that shows how it works.https://drive.google.com/open?id=1_ilwKHXTRBT250zB4At7UsbWJ09fQARlI tried to use different options, but I can not understand what is happening here.Could you give me advice how to fix it?
Posted
by John368.
Last updated
.
Post not yet marked as solved
0 Replies
592 Views
Hi everyone, An application has a Tab Bar Controller, two navigation stacks with navigation controllers, and two view controllers in each stack. In each navigation stack, the first view controller is a List of items, the second is the Detail screen, where I can edit an item from the list. The first navigation stack is Items, the second one is Orders. I can navigate inside this or that navigation stack using segues. But in this case, I need to move from one navigation stack to another. And to do this not with the help of a direct segue, because this is an incorrect method and it creates certain problems, but through the Tab Bar Controller. For example, to start to create an order, I can go from VC2.2 to VC1.1 using an index:         tabBarController?.selectedIndex = 0 And how to return back from VC1.1 to VC 2.2 via Tab Bar Controller and pass data?
Posted
by John368.
Last updated
.
Post not yet marked as solved
3 Replies
371 Views
Please, help me to understand one line of code.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {               if segue.identifier == "toDetailScreenSegue" { let detail = segue.destination as! DetailScreenViewController         detail.name = item.name         }     } What is happening in this line of code below? let detail = segue.destination as! DetailScreenViewController Is a copy of the DetailScreenViewController class being made? And since this is a class, not a structure, then not a separate copy is created, but a reference to the DetailScreenViewController class? Is this right?
Posted
by John368.
Last updated
.
Post not yet marked as solved
3 Replies
1k Views
I want to programmatically set the constraints for the view. I'm using the code from Apple's Swift library: Creating layout anchors // Get the superview's layout let margins = view.layoutMarginsGuide // Pin the leading edge of myView to the margin's leading edge myView.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true Link But my code doesn't work. import UIKit class ViewController: UIViewController {     var myView = UIView()     override func viewDidLoad() {         super.viewDidLoad()         myView.frame.size.width = 100         myView.frame.size.height = 100         myView.backgroundColor = .green         view.addSubview(myView)         let margins = view.layoutMarginsGuide         myView.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true     } } I am not getting any error messages. But my view always stays in the same place, in the upper left corner. Even if I change the constraint to center or bottom, the view doesn't move. Could you tell me what is wrong in my code?
Posted
by John368.
Last updated
.
Post marked as solved
1 Replies
705 Views
Hello everyone, recently I started to learn the SwiftUI. Now I have this code but I don't understand how can I call a view in canvas? At the first case I have error which says that argument is missing. import SwiftUI struct EmployeeDetails: View {     var employee: Employee     var body: some View {         VStack(alignment: .leading) {             Text(employee.name)                 .font(.largeTitle)                 .foregroundColor(.primary)             Text(employee.jobTitle)                 .foregroundColor(.secondary)             EmailAddress(address: employee.emailAddress)         }     } } struct EmployeeDetails_Previews: PreviewProvider {     static var previews: some View {         EmployeeDetails()     } } And when I use "employee" like argument in brackets, I have another error - can't find employee in scope. struct EmployeeDetails_Previews: PreviewProvider {     static var previews: some View {         EmployeeDetails(employee)     } } Please, help me to understand how can I call that view?
Posted
by John368.
Last updated
.
Post not yet marked as solved
4 Replies
3k Views
I want to create a button, but for some reason it does not work. The text message is not printed in the console. import SwiftUI struct Test: View {     var body: some View {         NavigationView {             Text("My Test")                 .navigationTitle("Welcome")                 .toolbar {                     Button("Help") {                         print("Help tapped!")                     }                 }         }     } } struct Test_Previews: PreviewProvider {     static var previews: some View {         Test()     } }
Posted
by John368.
Last updated
.
Post not yet marked as solved
0 Replies
377 Views
For some reason, the top of my table view in the storyboard has turned black. This is where the navbar and dynamic cell are. This happened after I tried to customize the appearance of the table view by changing the values of two options - Style and Separator (the screenshot) How do I get back the regular light color of the top of the table view? Xcode 13.2, macOS Monterey 12.1
Posted
by John368.
Last updated
.
Post marked as solved
5 Replies
859 Views
Hi everyone, I want to perform the tutorial from video WWDC19 - 204. Here is an example of building the "Rooms" application. At 42 minutes, the author of the video, Jacob Xiao, shows how to add a new room. But when I try to repeat it, nothing happens. The new room is not added. My code and code of Jacob Xiao are the same. import SwiftUI struct ContentView: View {     @ObservedObject var store = RoomStore()     // Instead of //var rooms: [Room] = []     // @ObservedObject is instead of @ObjectBinding     var body: some View {         NavigationView {             List {                 Button(action: addRoom) {                     Text("Add Room")                 }                 ForEach(store.rooms) { room in                     RoomCell(room: room)                 }             }             .navigationBarTitle(Text("Rooms"))         }     }     func addRoom() {         store.rooms.append(Room(name: "Hall 2", capacity: 2000))     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView(store: RoomStore(rooms: testData))     } } struct RoomCell: View {     var room: Room     var body: some View {         NavigationLink(destination: RoomDetail(room: room)) {             Image(room.thumbnailName)                 .cornerRadius(8)             VStack(alignment: .leading) {                 Text(room.name)                 Text("\(room.capacity) people")                     .font(.subheadline)                     .foregroundColor(.secondary)             }         }     } } My project has also an image named "Hall 2". What could be the reason that a new room is not being added? Any ideas, please.
Posted
by John368.
Last updated
.
Post marked as solved
11 Replies
1.3k Views
I want to mark the items in the list with checkmarks. But some kind of error occurs because the checkmark is installed, but not removed. Why is this happening? This is a Model: import UIKit struct Food: Codable {     var name: String     var isSelected: Bool = false } This is a TableViewController: import UIKit class SelectFoods: UITableViewController {     var foods = [Food]()     override func viewDidLoad() {         super.viewDidLoad()         foods = loadRealOrDemoData() // Load data     }     // MARK: - Table view data source     override func numberOfSections(in tableView: UITableView) -> Int {         return 1     }     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {         return foods.count     }     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {         let cell = tableView.dequeueReusableCell(withIdentifier: "selectFood", for: indexPath)         let food = foods[indexPath.row]         cell.textLabel?.text = food.name         // Assign checkmark from the selected item to the cell         if food.isSelected {             cell.accessoryType = .checkmark         } else {             cell.accessoryType = .none         }         cell.selectionStyle = .none         return cell     }     // MARK: - Select Food     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {         // Create variable and check it.         guard let cell = tableView.cellForRow(at: indexPath) else { return }          //Clean cell format before select         cell.accessoryType = .none         // Get an item         var item = foods[indexPath.row]         // Set checkmark         if item.isSelected == false {             cell.accessoryType = .checkmark             item.isSelected.toggle()         // Remove checkmark         } else {             cell.accessoryType = .none             item.isSelected.toggle()         }     } }
Posted
by John368.
Last updated
.
Post marked as solved
2 Replies
580 Views
I am using a date picker and want to assign the value from it to an object property. But for some reason this does not happen and the object property contains nil. I put code next to it where a date value is assigned to a simple property. It works. Please tell me what's the matter here? How do I store a date into a property of an object? import UIKit struct NewDate {     var date: Date? } class MyViewController: UIViewController {         var newDate: NewDate?         @IBOutlet weak var pickerOutlet: UIDatePicker!         override func viewDidLoad() {         super.viewDidLoad()         let date = pickerOutlet.date         print(date) // Prints: 2021-09-03 03:56:17 +0000         newDate?.date = pickerOutlet.date         print(newDate?.date) // Prints: nil     } }
Posted
by John368.
Last updated
.
Post marked as solved
5 Replies
679 Views
I want to use a Date Picker inside a TableViewCell but it shows some empty field - look the attached image. What is it and how to remove that empty field?
Posted
by John368.
Last updated
.
Post marked as solved
2 Replies
2.5k Views
Hi everyone, I want to perform the tutorial from video WWDC19 - 204. Here is an example of building the "Rooms" application. At 11 minutes, the author of the video, Jacob Xiao, shows how he performs the extract subview operation. But when I try to repeat this operation an error occurs - Cannot find 'room' in scope. My code and code of Jacob Xiao are the same. import SwiftUI struct ContentView: View {     var rooms: [Room] = []         var body: some View {         NavigationView {                         List(rooms) { room in                 ExtractedView()             }                       .navigationBarTitle(Text("Rooms"))         }     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView(rooms: testData)     } } struct ExtractedView: View {     var body: some View {         NavigationLink(             destination: Text(room.name)) { // Cannot find 'room' in scope             Image(room.thumbnailName)                 .cornerRadius(8)             VStack(alignment: .leading) {                 Text(room.name)                 Text("\(room.capacity) people")                     .font(.subheadline)                     .foregroundColor(.secondary)             }         }     } } I think the reason is that SwiftUI on my computer is a newer version, so some of the previous functions may not work. Could you tell me how to perform this subview extract operation today?
Posted
by John368.
Last updated
.