how to pass image and label from one viewController to tableViewCell swift? - arrays

Hi im trying to pass data from one viewController to tableViewCell without using the segue, i tried with delegate and nsNotificationCenter but it did not work with me so, help me please.
this is my code for the view controller which i want to pass data from it ( imageViewSweet, LabelSweet )
import UIKit
class sweetAndSalty4ViewController: UIViewController {
#IBOutlet var imageViewSweet: UIImageView!
#IBOutlet var labelsweet: UILabel!
#IBOutlet var sweeetTable: UITableView!
var passText: String?
override func viewDidLoad() {
passText = labelsweet.text
super.viewDidLoad()
}
#IBAction func sendData(_ sender: UIButton) {
let sb = storyboard?.instantiateViewController(withIdentifier: "cartVC") as! cartViewController
sb.priceLabel = labelsweet
present(sb, animated: true, completion: nil)
}
}
and this is the code for the viewController which i want to display the image and the label from the swwetAndSalty4ViewController .
import UIKit
class cartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var priceLabel: UILabel!
var passText: String?
var cartItem = ""
#IBOutlet var cartTable: UITableView!
override func viewDidLoad() {
cartTable.delegate = self
cartTable.dataSource = self
// foodTable.separatorStyle = .none
view.backgroundColor = UIColor.init(red: 228/255, green: 230/255, blue: 234/255, alpha: 1)
navigationItem.title = "My Cart"
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cartItem.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
240
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as! cartTableViewCell
cell.layer.cornerRadius = 30
cell.layer.borderWidth = 15.0
cell.layer.borderColor = UIColor.white.cgColor
cell.cartImage.layer.masksToBounds = true
cell.cartImage.layer.cornerRadius = 2
cell.cartImage.translatesAutoresizingMaskIntoConstraints = false
cell.cartImage.contentMode = .scaleAspectFill
cell.cartLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
cell.cartLabel.textColor = .black
cell.cartLabel.translatesAutoresizingMaskIntoConstraints = false
cell.cartLabel.backgroundColor = .systemGray5
cell.cartLabel.text = ""
cell.cartImage.image = UIImage(named: "")
// cell.contentView.backgroundColor = .white
return cell
}
}

There you go, i've also organized your code:
First View Controller:
import UIKit
struct myVariables {
static var kinder: String! = nil
static var kinderImage: UIImage! = nil
}
class sweetAndSalty4ViewController: UIViewController {
#IBOutlet var imageViewSweet: UIImageView!
#IBOutlet var labelsweet: UILabel!
#IBOutlet var sweeetTable: UITableView!
var passText: String?
override func viewDidLoad() {
super.viewDidLoad()
passText = labelsweet.text
}
#IBAction func sendData(_ sender: UIButton) {
let sb = storyboard?.instantiateViewController(withIdentifier: "cartVC") as! cartViewController
sb.priceLabel = labelsweet
present(sb, animated: true, completion: nil)
}
func sendDataToMyVariables(kinder: String, kinderImage: UIImage) {
myVariables.kinder = kinder
myVariables.kinderImage = kinderImage
}
}
and then, after you send the variables you can use them anywhere in your code by doing
myVariables.kinder // get the string
myVariables.kinderImage // get the image

Related

Handle items from multi viewController

Hi im trying to build ordering food application but i faced a problem which is i want to separate the cartTableViewController for multi viewController.
i don’t know how to explain it because my english is soo bad but i will try my best to explain it … what i mean is let say that the user has been added items from burgerKingViewController to the cartTableViewController and he move on to mcdonaldsViewController to add items to the cartTableViewController ,, here i want to show an alert for the user saying that he has an items in his cart from burgerKingViewController and he should delete it so he can add items from mcdonaldsViewController
to simplify it more .. i want the cartTableViewController handle only one restaurant so i can take the order from firebase.
thanks.
this is the code i use it to add the item to the cartTableViewController
import UIKit
struct userData {
static var selectedItem: Item? = nil
static var selectedItems: [Item] = []
static func selectedItemsPrice() -> Double {
var result: Double = 0
for item in selectedItems {
result = result + item.price
}
return result
}
static func allItemsToString() -> String {
var allNames: [String] = []
for item in selectedItems {
allNames.append(item.name)
}
return allNames.joined(separator: ", ")
}
}
struct Item: Equatable {
static let items : [Item] = {
let food: Item = .init(image: UIImage(named: “food”)!, name: “food, price: 50)
return [food]
}()
var image: UIImage?
var name: String
var price: Double
}
this is the cartTableViewController
import UIKit
class cartTableViewController: UITableViewController {
#IBOutlet var checkOutPressed: UIButton!
#IBOutlet var priceLabel: UILabel!
#IBOutlet var cartView: UIView!
#IBOutlet var totalOrder: UILabel!
#IBOutlet var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
checkOutPressed.layer.cornerRadius = 4.0
}
override func viewWillAppear(_ animated: Bool) {
priceLabel.text = "\(userData.selectedItemsPrice())"
totalOrder.text = "\(userData.allItemsToString())"
super.viewWillAppear(animated)
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userData.selectedItems.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
105
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as! cartTableViewCell
cell.cartImage.layer.masksToBounds = true
cell.cartImage.layer.cornerRadius = 8
cell.cartImage.translatesAutoresizingMaskIntoConstraints = false
cell.cartImage.contentMode = .scaleAspectFill
cell.cartLabel.textColor = .black
cell.cartLabel.translatesAutoresizingMaskIntoConstraints = false
cell.selectionStyle = .none
let cart = userData.selectedItems[indexPath.row]
cell.cartImage.image = cart.image
cell.cartLabel.text = cart.name
cell.priceLabel1.text = “\(cart.price)"
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
userData.selectedItems.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
priceLabel.text = "\(userData.selectedItemsPrice())"
totalOrder.text = "\(userData.allItemsToString())"
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
#IBAction func checkOutPressed(_ sender: UIButton) {
if priceLabel.text! == "" || totalOrder.text! == "" {
// Alert
let optionMenu = UIAlertController(title: nil, message: “please add item”, preferredStyle: .alert)
// Add actions to the menu
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler:
nil)
optionMenu.addAction(cancelAction)
// Display the menu
self.present(optionMenu, animated: true, completion: nil)
}
}
}
this is burgerKingViewController
import UIKit
class burgerKingViewController: UIViewController {
#IBOutlet var burgerKingImage: UIImageView!
#IBOutlet var burgerKingName: UILabel!
#IBOutlet var burgerKingPrice: UILabel!
#IBOutlet var makeOrder: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
makeOrder.layer.cornerRadius = 4.0
}
#IBAction func makeOrder(_ sender: UIButton) {
let alert = UIAlertController(title: "", message: “done”, preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
userData.selectedItems.append(Item(image: UIImage(named: “burgerKing”), name: “burgerKing”, price: Double(10.000)))
self.aimateView(sender)
}
fileprivate func aimateView( _ viewToAnimate:UIView) {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 0.92, y: 0.92)
}) { (_) in
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: nil)
}
}
}
and this is mcdonaldsViewController
import UIKit
class mcdonaldsViewController: UIViewController {
#IBOutlet var mcdonaldsImage: UIImageView!
#IBOutlet var mcdonaldsName: UILabel!
#IBOutlet var mcdonaldsPrice: UILabel!
#IBOutlet var makeOrder: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
makeOrder.layer.cornerRadius = 4.0
}
#IBAction func makeOrder(_ sender: UIButton) {
let alert = UIAlertController(title: "", message: “done”, preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
// change to desired number of seconds (in this case 5 seconds)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
userData.selectedItems.append(Item(image: UIImage(named: "mcdonalds"), name: "mcdonalds", price: Double(10.000)))
self.aimateView(sender)
}
fileprivate func aimateView( _ viewToAnimate:UIView) {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 0.92, y: 0.92)
}) { (_) in
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: nil)
}
}
}

Send array from custom cell to another view controller

i'm running a query to Firebase and the results are displaying in a custom cell. The cell has a UIButton that when tapped it goes to another view controller where the user can enter info. The question i have is, how do i send the array in the custom cell to the next view controller? i need to send the array so i can reference the subcollection of info i'm going to add for each array. Segue is working properly, when i print to the console, the array is empty "nil". Any help is greatly appreciated.
Custom Cell
import UIKit
import Firebase
protocol PatCellCommentsDelegate {
func patCommentBtnTapped (ptcomments: [Comment])
}
class PatdataCell: UITableViewCell {
#IBOutlet weak var ptnameLbl: UILabel!
#IBOutlet weak var dobLbl: UILabel!
#IBOutlet weak var finLbl: UILabel!
#IBOutlet weak var officemdLbl: UILabel!
#IBOutlet weak var assignedmdLbl: UILabel?
#IBOutlet weak var appnameLbl: UILabel!
#IBOutlet weak var assigneddateLbl: UILabel!
#IBOutlet weak var roomnumberLbl: UILabel?
#IBOutlet weak var diagnosesLbl: UILabel!
#IBOutlet weak var reasonforadmitorconsultLbl: UILabel!
#IBOutlet weak var goalofhospitalizationLbl: UILabel!
#IBOutlet weak var seenoseeLbl: UILabel?
#IBOutlet weak var notestocboLbl: UILabel!
#IBOutlet weak var numCommentsLbl: UILabel!
#IBOutlet weak var hospitalLbl: UILabel!
#IBOutlet weak var teamLbl: UILabel!
#IBOutlet weak var addCommentBtn: UIButton!
var ptdata: PTData!
var ptcomments = [Comment]()
var delegate: PatCellCommentsDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func configurePatDataCell(ptdata: PTData, delegate:
PatCellCommentsDelegate) {
self.ptdata = ptdata
self.delegate = delegate
ptnameLbl.text = ptdata.ptname
dobLbl.text = ptdata.dob
finLbl.text = ptdata.fin
officemdLbl.text = ptdata.officemd
assignedmdLbl?.text = ptdata.assignedmd
appnameLbl.text = ptdata.app
assigneddateLbl.text = ptdata.assigneddate
roomnumberLbl?.text = ptdata.room
diagnosesLbl.text = ptdata.diagnoses
reasonforadmitorconsultLbl.text = ptdata.reasonforadmitorconsult
goalofhospitalizationLbl.text = ptdata.goalofhospitalization
seenoseeLbl?.text = ptdata.seenosee
notestocboLbl.text = ptdata.notestocbo
numCommentsLbl.text = ptdata.comments
hospitalLbl.text = ptdata.hosp
teamLbl.text = ptdata.team
}
#IBAction func addCommentBtnTapped(_ sender: Any) {
//trying to send data to commentsVC from this cell
delegate?.patCommentBtnTapped(ptcomments: self.ptcomments)
}
}
View Controller
import UIKit
import Firebase
import SVProgressHUD
class PatdataVC: UIViewController, UITableViewDelegate,
UITableViewDataSource, PatCellCommentsDelegate {
#IBOutlet weak var patDataTableView: UITableView!
var ptdatas = [PTData]()
var ptComments = [Comment]()
override func viewDidLoad() {
super.viewDidLoad()
patDataTableView.delegate = self
patDataTableView.dataSource = self
patDataTableView.rowHeight = 1150
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToComments" {
let commtsVC = segue.destination as! CommentsVC
commtsVC.ptComments = ptComments
SVProgressHUD.dismiss()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return ptdatas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
if tableView == patDataTableView {
let cell = tableView.dequeueReusableCell(withIdentifier:
"PatdataCell", for: indexPath) as? PatdataCell
cell!.configurePatDataCell(ptdata: ptdatas[indexPath.row],
delegate: self)
return cell!
}
return UITableViewCell()
}
func patCommentBtnTapped (ptcomments: [Comment]) {
self.ptComments = ptcomments
performSegue(withIdentifier: "goToComments", sender: self)
}
}
CommentsVC
import UIKit
import Firebase
import FirebaseFirestore
class CommentsVC: UIViewController, UITableViewDelegate,
UITableViewDataSource, CommentsDelegate {
#IBOutlet weak var commentTableView: UITableView!
#IBOutlet weak var addCommentTxt: UITextField!
#IBOutlet weak var keyboardView: UIView!
var ptComments = [Comment]()
var commentsPtData: Comment!
var commentRef: DocumentReference!
var username: String!
var commentListener : ListenerRegistration!
let firestore = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
commentTableView.dataSource = self
commentTableView.delegate = self
commentTableView.rowHeight = 110
//commentRef =
firestore.collection(PTLIST_REF).document(commentsPtData.documentId)
// if let name = Auth.auth().currentUser?.displayName{
// username = name
// }
self.view.bindToKeyboard()
}
override func viewDidAppear(_ animated: Bool) {
commentListener =
firestore.collection(PTLIST_REF).document(self.commentsPtData
.documentId)
.collection(COMMENTS_REF)
.order(by: TIMESTAMP, descending: false)
.addSnapshotListener({ (snapshot, error) in
guard let snapshot = snapshot else {
debugPrint("Error Fetching comments: \(Error.self)")
return
}
self.ptComments.removeAll()
self.ptComments = Comment.parseData(snapshot: snapshot)
self.commentTableView.reloadData()
})
}
override func viewDidDisappear(_ animated: Bool) {
commentListener.remove()
}
func commentOptionsTapped(commentsCellPtData: Comment) {
let alert = UIAlertController(title: "Edit Comment", message: "You
can delete or edit", preferredStyle: .actionSheet)
let deleteAction = UIAlertAction(title: "Delete Comment", style:
.default) { (action) in
self.firestore.runTransaction({ (transaction, errorPointer) ->
Any? in
let ptListDocument: DocumentSnapshot
do {
try ptListDocument =
transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
} catch let error as NSError {
debugPrint("Fetch Error: \ .
(error.localizedDescription)")
return nil
}
guard let oldNumComments = ptListDocument.data()!
[NUM_COMMENTS] as? Int else { return nil }
transaction.updateData([NUM_COMMENTS : oldNumComments -
1], forDocument: self.commentRef!)
let commentRef =
self.firestore.collection(PTLIST_REF).document(self
.commentsPtData.documentId).collection(COMMENTS_REF)
.document(commentsCellPtData.documentId!)
transaction.deleteDocument(commentRef)
return nil
}) { (object, error) in
if let error = error {
debugPrint("transaction failed: \(error)")
} else {
alert.dismiss(animated: true, completion: nil)
}
}
}
let editAction = UIAlertAction(title: "Edit Comment", style:
.default) { (action) in
self.performSegue(withIdentifier: "toEditComment", sender:
(commentsCellPtData, self.commentsPtData))
alert.dismiss(animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel,
handler: nil)
alert.addAction(deleteAction)
alert.addAction(editAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
#IBAction func addCommentTapped(_ sender: Any) {
guard let commentTxt = addCommentTxt.text else { return }
firestore.runTransaction({ (transaction, errorPointer) -> Any? in
let ptListDocument: DocumentSnapshot
do {
try ptListDocument =
transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
} catch let error as NSError {
debugPrint("Fetch Error: \(error.localizedDescription)")
return nil
}
guard let oldNumComments = ptListDocument.data()!
[NUM_COMMENTS] as? Int else { return nil }
transaction.updateData([NUM_COMMENTS : oldNumComments + 1],
forDocument: self.commentRef!)
let newCommentRef =
self.firestore.collection(PTLIST_REF).document((self
.commentsPtData.documentId)).collection(COMMENTS_REF).document()
transaction.setData([
COMMENT_TXT : commentTxt,
TIMESTAMP : FieldValue.serverTimestamp(),
USERNAME : self.username!,
USER_ID : Auth.auth().currentUser?.uid ?? ""
], forDocument: newCommentRef)
return nil
}) { (object, error) in
if let error = error {
debugPrint("transaction failed: \(error)")
} else {
self.addCommentTxt.text = ""
self.addCommentTxt.resignFirstResponder()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return ptComments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier:
"CommentCell", for: indexPath) as? CommentCell {
cell.configureCell(comment: ptComments[indexPath.row],
delegate: self)
return cell
}
return UITableViewCell()
}
}
In your source code ptcomments property in Custom Cell not set anywhere, it is empty in cell.
Please set correct value for ptcomments
UPDATE:
You try add line like self.comments = ptdata.commentsList to function configurePatDataCell

How to access UILabel in custom cell with indexPath and implement user data from array/ dictionary into the label

I have been trying to fix this for 4 days and still no luck so any help would be appreciated. I am trying to create a table view where workers can upload their profiles and users can scroll through to see which ones they like (see simulator photo). However, when I use indexPath.row it fills out the whole cell when I only want it to fill out one label so I can configure the different labels with the data I want.
Here is my Table view controller code:
import UIKit
import FirebaseDatabase
import FirebaseStorage
struct Worker {
var name: String!
var price: String!
}
class SelectATaskerTableViewController: UITableViewController {
var ref: DatabaseReference!
var myList:[String] = []
#IBOutlet var myTableView: UITableView!
var handle: DatabaseHandle!
var storageHandle: StorageHandle!
var storageRef: StorageReference!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 111
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func viewWillAppear(_ animated: Bool) {
myTableView.delegate = self
myTableView.dataSource = self
ref = Database.database().reference()
storageRef = Storage.storage().reference()
handle = ref.child("WorkerProfile").child("Name").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? String {
self.myList.append(item)
self.myTableView.reloadData()
}
})
}
#IBAction func reset(_ sender: Any) {
Database.database().reference().child("WorkerProfile").removeValue()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return myList.count
}
var nameText: String!
var pricePerHourText: String!
var extraDetailsText: String!
var profilePicImage: UIImage!
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCellTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCellTableViewCell
cell.firstName.text = myList[indexPath.row]
cell.pricePerHour.text = myList[indexPath.row]
// cell.extraDetails.text = extraDetailsText
// cell.profilePic.image = profilePicImage
// Configure the cell...
return cell
}
And my custom table view cell code
import UIKit
class MyCellTableViewCell: UITableViewCell {
#IBOutlet weak var firstName: UILabel!
#IBOutlet weak var pricePerHour: UILabel!
#IBOutlet weak var extraDetails: UILabel!
#IBOutlet var profilePic: UIImageView!
}

Table View To seperate view with segue

This has stumped me and Ive tried a few ways of doing of tutorials and on stack answers but its still not building.
So basically:
Im getting core data and then placing that into an array. (works fine)
After that Im just display first and last name in the cells (works fine)
User taps on cell to see athleteDetalView
I have placed a few print statements to see where its going wrong.
Thanks In advance for your input.
import UIKit
import CoreData
class athleteViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//labels
#IBOutlet weak var athleteLabel: UILabel!
//buttons
#IBOutlet weak var athleteCreate: UIBarButtonItem!
#IBOutlet weak var athleteTableView: UITableView!
var athleteArray:[Athlete] = []
var myIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
athleteTableView.delegate = self
athleteTableView.dataSource = self
self.fetchData()
self.athleteTableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return athleteArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "athleteName", for: indexPath)
let name = athleteArray[indexPath.row]
cell.textLabel!.text = name.firstName! + " " + name.lastName!
let athleteName = name.firstName!
let lastName = name.lastName!
let age = name.age!
let sport = name.sport!
let email = name.email!
print(athleteName)
print(lastName)
print(age)
print(sport)
print(email)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
let currentCell
//let storyboard = UIStoryboard(name: "Main", bundle: nil)
//let destination = storyboard.instantiateViewController(withIdentifier: "athleteDetailsViewController") as! athleteDetailsViewController
//let athName = athleteArray[myIndex]
//testdata
//test data
performSegue(withIdentifier: "athleteDetailsSegue", sender: self)
//self.navigationController?.pushViewController(destination, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "athleteDetailsSegue") {
var destination = segue.destination as! athleteDetailsViewController
destination.firstNameString = athleteName
destination.lastNameString = lastName
destination.ageString = age
destination.sportString = sport
destination.emailString = email
//destination.getImage = name.image
}
}
func fetchData(){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do{
athleteArray = try context.fetch(Athlete.fetchRequest())
}
catch{
print(error)
}
}
The variables that you are setting in tableView:cellForRowAt:indexPath: are local variables and are not available in the function prepareForSegue:. Try to declaring the variables at the top as properties of the class.

How to make a button, which adds new row with array data in TableView inside ViewController(they are not separate view controllers!)?

I am making a game using swift, and I want to make a history of answers. But the problem is Xcode tells thread1 exc_bad_instruction when I click button "addResult". Here is the code. Before launching the simulator and even after launching there is no error shown, however, when I click the "addResult" button the app crashes.
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var choice1Text: UITextField!
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var choice2Text: UITextField!
#IBOutlet var mytableView: UITableView! {
didSet {
mytableView.dataSource = self
}
}
var items: [ResultlistItem]
required init?(coder aDecoder: NSCoder) {
items = [ResultlistItem]()
let row0item = ResultlistItem()
row0item.text = "Yes"
items.append(row0item)
let row1item = ResultlistItem()
row1item.text = "No"
items.append(row1item)
super.init(coder: aDecoder)
}
}
#IBAction func addResult(sender: AnyObject) {
let item = ResultlistItem()
item.text = "new one"
items.append(item)
mytableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Resultitem", for: indexPath)
let item = items[indexPath.row]
configureText(for: cell, with: item)
return cell
}
func configureText(for cell: UITableViewCell, with item: ResultlistItem) {
let label = cell.viewWithTag(1000) as! UILabel
label.text = item.text
}

Resources