Post not yet marked as solved
Now I only see top posts. But it would be better to see all the new topics that have been created in recent days.
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?
Post not yet marked as solved
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.
Post not yet marked as solved
Hi everyone,can someone explain to me why, every time I reinstall the xcode, a message appears that I need to install additional components? Is this the way it should be, or is it some kind of hacker program trying to install on my computer?Any help would appreciate.
Post not yet marked as solved
Today I have reinstall Xcode (11.3.1, Catalina).As soon as I launched it, such a message appeared:Install additional required componentsXcode requires additional components to support running and debugging. Choose Install to add required components.Can someone explain to me what these additional components are? And why aren't they included in Xcode by default?Maybe there is some of the employees of the Apple company on this forum who could explain this issue? Because I have a suspicion that some malware calls itself Xcode and wants to install something harmful on my computer.
Post not yet marked as solved
I use Xcode every day. Today, a message suddenly appeared - "Developer Tools Access needs to take control of another process for debugging to continue"This has not happened before. I recently installed a clean Catalina, Xcode 11.3, swift 5.1Did anyone have such a message? Could you help me understand what to do is better in this situation?
Post not yet marked as solved
When I use Xcode it regular shows me a message "Xcode requires additional components..."It was earlier, when I used Hi Sierra and Xcode 10, and today, when I installed Catalina and Xcode 11.What is it? Is it normally or it is a problem? Can anybody help me to make clear this question?
Post not yet marked as solved
Apple has released a new book on learning to programming - AP® Computer Science Principles with Swift.What do you think about it?
For some reason, the value is lost when I try to transfer it from ViewController to TableViewController. The scheme seems to be simple, the value is taken from the first TVC (such as a warehouse) and transmitted to the VC (details), and from there to the order basket or cart - to the second TVC. And when I try to pass data to the cart, it pass only one value. I.e. if I try pass next item in Cart I see only one value in the Cart. It seems that append() method doesn't work, array always contains only one item.What is wrong here?Model:import Foundation
import UIKit
struct Bouquet {
var name: String
}First TVC:import UIKit
class BouquetsTableViewController: UITableViewController {
var bouquets = [Bouquet]()
var bouquet: Bouquet?
override func viewDidLoad() {
super.viewDidLoad()
bouquets = [
Bouquet(name: "Flower 1"),
Bouquet(name: "Flower 2"),
Bouquet(name: "Flower 3"),
Bouquet(name: "Flower 4"),
Bouquet(name: "Flower 5"),
Bouquet(name: "Flower 6")
]
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bouquets.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "bouquetsCell", for: indexPath)
cell.textLabel?.text = bouquets[indexPath.row].name
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "GoToDetails" else { return }
let indexPath = tableView.indexPathForSelectedRow
bouquet = bouquets[(indexPath?.row)!]
let detailsVeiwController = segue.destination as! DetailsViewController
detailsVeiwController.bouquet = bouquet
}
@IBAction func unwindToBouquets(_ unwindSegue: UIStoryboardSegue) {
}
}VC:import UIKit
class DetailsViewController: UIViewController {
var bouquet: Bouquet?
var itemToCart = ""
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var imageLabel: UIImageView!
@IBAction func addToCartButton(_ sender: UIButton) {
itemToCart = nameLabel.text!
}
@IBAction func viewCartButton(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = bouquet?.name
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "addToCart" else { return }
let cartTableViewController = segue.destination as! CartTableViewController
cartTableViewController.cartItem = bouquet!
}
}Second TVC:import UIKit
class CartTableViewController: UITableViewController {
var cartItems = [Bouquet]()
var cartItem: Bouquet? {
didSet {
guard let item = cartItem else { return }
cartItems.append(item)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
// 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: "CartCell", for: indexPath)
cell.textLabel?.text = cartItems[indexPath.row].name
return cell
}
}
Post not yet marked as solved
Hi, I study Augmented Reality and have some questions. On page 459 author of this textbook say to add a new node with next code:let node = SCNNode()
node.position = SCNVector3(0.0, 0.2, 0.0)Please tell me where, in what place, I should to insert this code? Into viewDidLoad method or other?
Post not yet marked as solved
Hi there,I have one bug on this forum. When I copy-paste some text to the field of answer, the window is jumping and focus fall down, bellow the field. This is not comfortable.This bug is only in Safari and in different versions of Mac OS.
Post not yet marked as solved
I'm a beginner, please help me to understand why it happens?I have two TableViewCotrollers - dynamic and static. When I add or edit item in static TVC it pass to the dynamis TVC. This data is visible in the table. But after that it is not saved. When i open the app again these changes are missing and if I roll the wheel of the pickerView these changes disappear.I put the function of saving to file on disk wherever possible, but it still does not work. What is my mistake?TVC 1 - Dynamicimport UIKit
class StudentsTableViewController: UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var pickerViewStudents: UIPickerView!
var classesObject = [ClassUnit]()
var classSelected: String = ""
var studentsSelected: [String] = [] {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.pickerViewStudents.delegate = self
self.pickerViewStudents.dataSource = self
classesObject = ClassUnit.loadFromFile()
navigationItem.leftBarButtonItem = editButtonItem
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return classesObject.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
classesObject = ClassUnit.loadFromFile()
return classesObject[row].classTitle
}
override func viewWillAppear(_ animated: Bool) {
classesObject = ClassUnit.loadFromFile()
pickerViewStudents.reloadAllComponents()
tableView.reloadData()
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
classSelected = classesObject[row].classTitle
studentsSelected = classesObject[row].classStudents
ClassUnit.saveToFile(classes: classesObject)
}
// MARK: - Table view data source//
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return studentsSelected.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ClassTitleStudents", for: indexPath)
cell.textLabel?.text = studentsSelected[indexPath.row]
cell.showsReorderControl = true
ClassUnit.saveToFile(classes: classesObject)
return cell
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) ->
UITableViewCellEditingStyle {
return .delete
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
studentsSelected.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
ClassUnit.saveToFile(classes: classesObject)
}
}
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let moveStudent = studentsSelected.remove(at: fromIndexPath.row)
studentsSelected.insert(moveStudent, at: to.row)
tableView.reloadData()
ClassUnit.saveToFile(classes: classesObject)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditStudentSegue" {
let indexPath = tableView.indexPathForSelectedRow!
let student = studentsSelected[indexPath.row]
let nav = segue.destination as! UINavigationController
let editStudentName = nav.topViewController as! AddEditStudentTableViewController
editStudentName.student = student
ClassUnit.saveToFile(classes: classesObject)
}
}
@IBAction func unwindToStudentsTableView(segue: UIStoryboardSegue) {
guard segue.identifier == "saveUnwindStudents" else { return }
let sourceViewController = segue.source as! AddEditStudentTableViewController
let student = sourceViewController.student
if let selectedIndexPath = tableView.indexPathForSelectedRow {
studentsSelected[selectedIndexPath.row] = student
tableView.reloadRows(at: [selectedIndexPath], with: .none)
ClassUnit.saveToFile(classes: classesObject)
} else {
let newIndexPath = IndexPath(row: studentsSelected.count, section: 0)
studentsSelected.append(student)
//tableView.insertRows(at: [newIndexPath], with: .automatic)
ClassUnit.saveToFile(classes: classesObject)
}
}
}TVC 2 - Staticimport UIKit
class AddEditStudentTableViewController: UITableViewController {
@IBOutlet weak var nameStudent: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
var classesObject = [ClassUnit]()
var student = ""
override func viewDidLoad() {
super.viewDidLoad()
nameStudent.text = student
updateSveButton()
classesObject = ClassUnit.loadFromFile()
}
func updateSveButton() {
let nameOfStudent = nameStudent.text ?? ""
saveButton.isEnabled = !nameOfStudent.isEmpty
ClassUnit.saveToFile(classes: classesObject)
}
@IBAction func textEditingChanged(_ sender: UITextField) {
updateSveButton()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "saveUnwindStudents" else { return }
let nameOfStudent = nameStudent.text ?? ""
student = nameOfStudent
ClassUnit.saveToFile(classes: classesObject)
}
}
Hello,I'm a beginner with Swift and I'm struggling to understand the way the variables are send between class one and class two using protocol.I want to create a data model for monitoring the heart rate. This data is displayed on the screen so that the user can see them. In parallel, it needs to check this data, i.e. print to the console what the label shows. I can not understand why the delegate property does not get a value (it has always nil) and why it does not print a phrase about what the user sees?Technologies: XCODE Version 9.2, swift 4.How can I solve this?Thanks in advance.CODE:import UIKit
protocol HeartRateReceiverDelegate {
func heartRateUpdated(to bpm: Int)
}
class HeartRateReceiver {
var delegate: HeartRateReceiverDelegate?
var currentHR: Int? {
didSet {
if let currentHR = currentHR {
print("The most recent heart rate reading is \(currentHR).")
delegate?.heartRateUpdated(to: currentHR)
print("CurrentHR is \(currentHR)") // Check value
print("Delegate is \(delegate)") // Check value
} else {
print("Looks like we can't pick up a heart rate.")
}
}
}
func startHeartRateMonitoringExample() {
for _ in 1...10 {
let randomHR = 60 + Int(arc4random_uniform(UInt32(15)))
currentHR = randomHR
Thread.sleep(forTimeInterval: 2)
}
}
}
class HeartRateViewController: UIViewController, HeartRateReceiverDelegate {
var heartRateLabel: UILabel = UILabel()
func heartRateUpdated(to bpm: Int) {
heartRateLabel.text = String(bpm)
print("The user has been shown a heart rate of heartRateLabel.text")
}
}
let heartRateReceiver = HeartRateReceiver()
heartRateReceiver.startHeartRateMonitoringExample()
var heartRateViewController = HeartRateViewController()
heartRateReceiver.delegate = heartRateViewController
Post not yet marked as solved
Hello, I encountered with such a problem. In the code below, the guard statement does not fire.struct Person {
var firstName: String
var lastName: String
var age: String
}
let firstNameTextField = UITextField()
let lastNameTextField = UITextField()
let ageTextField = UITextField()
firstNameTextField.text = "John"
lastNameTextField.text = "Williams"
ageTextField.text = nil
func createPerson() -> Person? {
guard let firstNameUnwrap = firstNameTextField.text else { return nil }
guard let lastNameUnwrap = lastNameTextField.text else { return nil }
guard let ageUnwrap = ageTextField.text else { return nil }
return Person(firstName: firstNameUnwrap, lastName: lastNameUnwrap, age: ageUnwrap)
}
if let personNew = createPerson() {
print(personNew.firstName, personNew.lastName, personNew.age)
}
// Print: John WilliamsWhy the guard statement doesn't work here?