Post

Replies

Boosts

Views

Activity

How to pass data through TabBarController?
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?
13
0
6.7k
Jun ’19
How to avoid a massive controller?
Hi everybody, I am a beginner developer and in my Shopping List application I faced a problem of a massive controller. I have read several articles on this topic. They helped me to understand some things, but they don't solve this problem completely. Therefore, I decided myself to try to organize the structure of the view controller in terms of the tasks to be solved. For example, my application has a table view controller (screen) for list of items. This TVC should perform the following main tasks: Show list of Items. Select items for Shopping. In turn, the first main task includes the following actions: Show data in a table Supporting Edit Actions - Add, Delete, and Change Data. Supporting Usability Action - Sort (reorder, rearrange) Data. The second main task includes the following actions: Mark Items with a Checkmarks In addition, this TVC should to save and load data. Common / General Supporting Tasks for Both Main Tasks: Save data to the archive file Load Data from the archive file When I implemented all the functions of the controller, I got the following real structure: Supporting Common / General Task: Load data Load data from database Load/Update data after changing in other View Controllers Main Task 1: Show data in a table. numberOfSections numberOfRowsInSection cellForRowAt Supporting Edit Task for Main Task 1: Add a new item. Calling a method from an Extension Supporting Edit Tasks for Main Task 1: Delete and Change actions leadingSwipeActions deleteAction changeAction Unwind Action - Return from Change Screen for Cancel button Supporting Usability Task for Main Task 1: Sort list of items. Show sort/reorder/rearrange button and its title Which rows can be reordered (Allow to reorder) Reorder items in list Remove Delete button from screen Main Task 2: Select items (mark them with checkmarks) didSelectRowAt Supporting Usability Task for Main Task 2: Clear all Checkmarks. Uncheck all items button Supporting Common / General Task: Persist Data (Save data to the archive file) Save/persist data before View will disappear  viewWillDisappear Could you tell me is this approach optimal? May I have some other problems later which I do not know about yet? Any ideas are appreciated.
0
0
363
Jul ’20
Why doesn't the app work 6 seconds after launch?
Hi everybody, There is one strange problem in my application. When the application is launched on the phone for the first time, it does not work for the first six seconds. After that everything works fine. The app also works fine when re-launched on the phone and when launched on the simulator. The application itself is small and not complicated, all data is stored on the device. It uses a Tab Bar Controller with three tabs. Another strange feature is that if I click on the icons in these first six seconds, then nothing works right away, but then all the commands are executed. Those, it looks like the application has accepted the commands, but it takes a long time to execute them. Has anyone faced such a problem? What could be causing this? Any ideas are appreciated. Swift 5.2, Xcode 11.6, macOS Catalina 10.5.6
4
0
667
Aug ’20
Why isn't the value assigned to the cell label of the static table?
I create a Detail screen using a standard TableViewController. The TableView-Content option is Static Cells, the Table View Sell-Style option is Basic. The label is used by default, not custom. With the help of this line of code below, I try to pass a value to the label: tableView.cellForRow(at: [0,0])?.textLabel?.text = item!.itemID The value comes to the controller, I see it, but for some reason it is not displayed on the label and displays a nil in the debugger. What could be the mistake?
4
0
551
Sep ’20
Landmarks Tutorial. Preview doesn't work
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)")     } }
9
1
3.5k
Mar ’21
How to Choose the WatchLandmarks target in SwiftUI Tutorial?
Hi everyone, I am studying SwiftUI on the Apple tutorial - https://developer.apple.com/tutorials/swiftui/creating-a-macos-app. In the Creating a MacOS App chapter in section 3 Update a Row View, there is a following instruction: Step 6 Choose the WatchLandmarks target to see a watchOS preview of the list. How to do this? It should be easy and simple, but somehow I haven't found it.
1
0
613
Apr ’21
How to perform extract subview operation?
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?
2
0
3.2k
Aug ’21
Why isn't the date assigned to the object property?
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     } }
2
0
817
Sep ’21
Checkmarks are not removed from the table cell
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()         }     } }
11
0
1.9k
Sep ’21
Why isn't a new room created in the Rooms project? SwiftUI, WWDC19-204
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.
5
0
1.3k
Oct ’21