Swift 4 Switch relate to label on tableView - swift

I have problem to get label from cell when i turn my switch ON. I do fetch all labels from Firebase Database.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tagCell", for: indexPath) as! TagsTableViewCell
print(myCallList[indexPath.row])
let _tag = myCallList[indexPath.row]
cell.tagLabel?.text = _tag.type
return cell
}
UPDATED:
UITableViewCell contain nothing special
import UIKit
class TagsTableViewCell: UITableViewCell {
#IBOutlet weak var tagLabel: UILabel!
#IBOutlet weak var tagSwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
My model:
class Calls: NSObject {
var type: String?
init(type: String?) {
self.type = type
}
}
LoadCalls contain Firebase data fetch:
func LoadCalls() {
ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
self.myCallList.removeAll()
ref.child("tags").observe(.childAdded, with: { (snapshot) in
if snapshot != nil{
var tagType = snapshot.key as? String
let myCalls = Calls(type: tagType)
self.myCallList.append(myCalls)
print(self.myCallList.count)
DispatchQueue.main.async {
self.tagsTableView.reloadData()
}
}
})
}

A delegate / protocol for communication between cell and table controller can work well here.
protocol switchCellDelegate : Class {
func cellSwitchChanged( value: String, sender: Any)
}
update table view cell with property and IBAction for switch change
class TagsTableViewCell: UITableViewCell {
weak var delegate : switchCellDelegate?
#IBAction func switchChanged(sender: UISwitch){
guard let delegate = delegate else { return }
if sender.isOn {
delegate.cellSwitchChanged( value: tagLabel.text, sender: self)
}
}
and then in cellForRowAtIndex, add this
cell.delegate = self
and controller
extension myController : switchCellDelegate {
func cellSwitchChanged( value: String, sender: Any){
//do what you want here
}
}

I guess it something like this - add tag to switcher and create action for it
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tagCell", for: indexPath) as! TagsTableViewCell
print(myCallList[indexPath.row])
let _tag = myCallList[indexPath.row]
cell.tagLabel?.text = _tag.type
cell.switcher.tag = indexPath.row
return cell
}
And after this
#IBAction func switcherChanged(_ sender: UISwitch) {
var getLabel = myCallList[(sender as AnyObject).tag]
print(getLabel.type)
}

Related

DidSelectRow function is not called

I'm trying to implement the didSelectRow function and perform a segue but when running the cells select and nothing happens.
I created a print statement that also doesn't run which proves that the function doesn't appear to be firing. Why would this be?
I have checked the identifier is correct and have researched these for a few hours going through many stack overflow threads but with little luck.
import UIKit
import CoreData
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let viewController = ListNameViewController()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
var itemChoosen = 0
override func viewDidLoad() {
super.viewDidLoad()
homeListsTableView.delegate = self
homeListsTableView.dataSource = self
viewController.loadList()
}
#IBOutlet weak var homeListsTableView: UITableView!
#IBAction func templatesButton(_ sender: Any) {
tabBarController?.selectedIndex = 2
}
#IBAction func allListsButton(_ sender: Any) {
tabBarController?.selectedIndex = 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewController.listName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let result = viewController.listName[indexPath.row]
cell.textLabel?.text = ("\(String(result.listName!))")
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
context!.delete(viewController.listName[indexPath.row])
viewController.listName.remove(at: indexPath.row)
viewController.saveList()
homeListsTableView.reloadData()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "items2", sender: self)
print("selected")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
viewController.loadList()
homeListsTableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
homeListsTableView.reloadData()
}
}
ListNameViewController:
import UIKit
import CoreData
class ListNameViewController: UIViewController, UITableViewDelegate {
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
var listName : [ListName] = []
override func viewDidLoad() {
super.viewDidLoad()
createButtonChange.isEnabled = false
//Objective-C Line used to keep checking if the text field is vaild before enabling the submit button
listNameValue.addTarget(self, action: #selector(textValidation), for: UIControl.Event.editingChanged)
}
#IBOutlet weak var listNameValue: UITextField!
#IBOutlet weak var locationOption: UITextField!
#IBOutlet weak var createButtonChange: UIButton!
#objc func textValidation() {
//Text Field Validation check before button is enabled
if listNameValue.text!.isEmpty {
createButtonChange.isEnabled = false
} else {
createButtonChange.isEnabled = true
}
}
// Create a new List
#IBAction func createButton(_ sender: Any) {
let newList = ListName(context: context!)
newList.listName = listNameValue.text
saveList()
self.navigationController!.popViewController(animated: true)
viewWillAppear(false)
}
func saveList() {
do {
try context!.save()
} catch {
print("Error saving context \(error)")
}
}
func loadList() {
let request : NSFetchRequest<ListName> = ListName.fetchRequest()
do{
listName = try context!.fetch(request)
} catch {
print("Error loading categories \(error)")
}
}
//Pass data to the HomeViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// let vc = segue.destination as! HomeViewController
}
}
// commented out core data and just used a normal array for testing.
Did you add segue in your storyboard for the tableview ? In this case the didSelect is not call but the prepare(for segue) of the tableview controller is called.
Ok solved it - There was a rouge tap gesture recognizer on the page. Removed it and works on one click. I have seen that if you wish to keep the gesture just add this line of code at the top of the function:
tap.cancelsTouchesInView = false
Took three days but I got there. Thanks for the help!

How do I rename a button in a different View controller with a firebase username from a UIView cell?

I am trying to rename the "Add Bodyguard" button with a username from my firebase database when that user is selected from the cell
// Code for the contacts page where a user is selected from cell.
class ContactsTableViewController: UITableViewController {
var ref: DatabaseReference!,
posts = [eventsStruct]()
let cellId = "cellId"
var users = [CurrentUser]()
struct eventsStruct {
let email: String!
let username: String!
let phoneNumber: String!
}
override func viewDidLoad() {
super.viewDidLoad()
fetchUser()
}
func fetchUser() {
ref = Database.database().reference()
ref.child("Users").queryOrderedByKey().observe(.childAdded, with:{(snapshot) in
if let usersDictionary = snapshot.value as? [AnyHashable:String]
{
let email = usersDictionary["email"]
let username = usersDictionary["username"]
let phoneNumber = usersDictionary["phoneNumber"]
self.posts.insert(eventsStruct (email: email, username: username, phoneNumber: phoneNumber), at: 0)
DispatchQueue.main.async {
self.tableView.reloadData()
}
print(eventsStruct.init(email: email, username: username, phoneNumber: phoneNumber))
}
})
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
var homeViewController: HomeViewController?
//tap to dismiss contacts page
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dismiss(animated: true) {
print("dismiss completed")
let user = self.posts[indexPath.row]
self.homeViewController?.addBodyguard.setTitle(user.email, for: .normal)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
// let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
let user = posts[indexPath.row]
cell.textLabel?.text = user.username
cell.detailTextLabel?.text = user.phoneNumber
return cell
}
#IBAction func cancelTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
// the HOMEVIEWcontroller containing the button to be renamed
class HomeViewController: UIViewController, UISearchBarDelegate, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var addBodyguard: UIButton!
#IBAction func Addguard(_ sender: Any) {
self.performSegue(withIdentifier: "contactsSegue", sender: nil)
}
}
Rather than setting the UIButtons's title in ContactViewController you should use delegate to pass this event to HomeViewController.
protocol ContactSelectionDelegate {
func contactSelected(email: String) -> Void
}
extension HomeViewController: ContactSelectionDelegate {
func contactSelected(email: String) -> Void {
self.addBodyguard.setTitle(email, for: .normal)
}
}
// In your HomeViewController
#IBAction func Addguard(_ sender: Any) {
self.performSegue(withIdentifier: "contactsSegue", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "contactsSegue")
{
let secondViewController = segue.destinationViewController as! ContactViewController
secondViewController.delegate = self
}
}
// In your ContactViewController
class ContactViewController {
....
weak var delegate: ContactSelectionDelegate?
...
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dismiss(animated: true) {
print("dismiss completed")
let user = self.posts[indexPath.row]
self.delegate?.contactSelected(email: user.email)
}
}
}
The usual convention in Model-View-Controller designs like UIKit is to not reach from one ViewController into the other.
Instead, there are alternate approaches:
Give the class that knows that the new name should be on the button a delegate property and make the other controller its delegate and notify it. (others have answered this in detail)
Have a shared model object that contains the user name, and have both controllers display their data based on that model object. In that case, your Firebase controller would write the new name to the model, which would make the button's controller notice the property changed and change the button name.
Send a Notification (using NotificationCenter). I wouldn't do that in this case. Notifications are generally best used for things that interest large parts of the application, as anyone can subscribe to them. So they kind of weaken your class's encapsulation. It can also be a bit involved to find all the places that respond to a notification when debugging.

How to use NSPredicate to fetch request and populate second viewController with data when UItableView roll is pressed in first viewController

I'm coding a Note App in Swift 4. The root ViewController (NoteListViewController) gets populated when secondViewController (ComposeNoteViewController) Textfield and TextView are populated.
The problem is when I press a populated TableView cell, rather than fetch and display the content, it opens a fresh instance of theComposeNoteViewController.
import UIKit
import CoreData
class NoteListTableViewController: UITableViewController {
var noteListArray = [NoteListItem]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
loadNoteListItem()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return noteListArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NoteListItemCell", for: indexPath)
cell.textLabel?.text = noteListArray[indexPath.row].title
return cell
}
//MARK: - TABLEVIEW DELEGATE METHODS
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToComposeNote", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! ComposeNoteViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedNoteList = noteListArray[indexPath.row]
}
}
import UIKit
import CoreData
class ComposeNoteViewController: UIViewController {
var noteComposeItemsArray = [ComposeNote]()
var noteListArray = [NoteListItem]()
// let noteListController = NoteListTableViewController()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var selectedNoteList : NoteListItem? {
didSet {
loadComposeItem()
}
}
#IBOutlet weak var noteTextView: UITextView!
#IBOutlet weak var noteTextField: UITextField!
#IBAction func noteSavePressed(_ sender: UIBarButtonItem) {
let newNoteTitleItem = NoteListItem(context: context)
let newComposeNote = ComposeNote(context: context)
newNoteTitleItem.title = noteTextField.text!
newComposeNote.note = noteTextView.text!
newComposeNote.parentTitleNote = selectedNoteList
noteComposeItemsArray.append(newComposeNote)
noteListArray.append(newNoteTitleItem)
saveComposeItems()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func saveComposeItems() {
do {
try context.save()
}catch {
print("Error saving context \(error)")
}
reloadInputViews()
}
func loadComposeItem() {
let request : NSFetchRequest<ComposeNote> = ComposeNote.fetchRequest()
let predicate = NSPredicate(format: "parentTitleNote.title MATCHES %#", selectedNoteList!.title!)
request.predicate = predicate
do {
noteComposeItemsArray = try context.fetch(request)
}catch {
print("Can't load Items")
}
reloadInputViews()
}
}

UITableview cells aren't showing

UITableview is visible while the cells aren't.
This is for a food ordering app, and I'm trying to display the menu. I've tried everything, no error has shown, but the cells ain't visible
import UIKit
import FirebaseDatabase
import FirebaseCore
class MenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var menu = [Food]()
var ref: DatabaseReference?
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
ref = Database.database().reference()
loadMenu()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menu.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell") as? MenuCell {
let foodItem = menu[indexPath.row]
cell.configCell(food: foodItem)
return cell
}else{
return UITableViewCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "popup", sender: menu[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let popupVC = segue.destination as? MenuPopUpVC {
if let foodItem = sender as? Food{
popupVC.config(food: foodItem)
}
}
}
func loadMenu() {
ref?.child("menu").observe(.value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let foodName = dict["name"] as! String
print(foodName)
let foodPrice = dict["price"] as! String
let foodImg = dict["image"] as! String
let foodItem = Food(name: foodName, price: foodPrice, img: foodImg)
self.menu.append(foodItem)
}
})
}
}
import UIKit
import SDWebImage
class MenuCell: UITableViewCell {
#IBOutlet weak var PriceLbl: UILabel!
#IBOutlet weak var menuImg: UIImageView!
#IBOutlet weak var menuItemLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configCell(food : Food) {
let name = food.name ?? ""
menuItemLbl.text = name
let price = food.price ?? ""
PriceLbl.text = "$\(price)"
menuImg.sd_setImage(with: URL(string: food.img!)) {[weak self] (image, error, cachetype, url) in
if error == nil{
self?.menuImg.image = image
}
}
}
}
You don't reload data of your TableView, reload them after you append all foods to menu array (means after foreach loop)
ref?.child("menu").observe(.value, with: { (snapshot) in
for child in snapshot.children {
...
self.menu.append(foodItem)
}
self.tableView.reloadData()
})
You need to reload the tableView after you fill the array
self.menu.append(foodItem)
}
self.tableView.reloadData()
Also inside cellForRowAt , it's a good practice to
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell") as! MenuCell
without the misleading return UITableViewCell()

unable to save on/off state of a UITableViewCell?

there are two attributes 'time' and 'isOn' (string, bool) in the entity named 'Item'
in viewcontroller class I am able to give default condition to 'isOn' attribute (in savePressed function) which makes switchbtn.isOn = true and saves it in the data model for that particular 'time'
viewcontroller class :-
class ViewController: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet weak var timePickerView: UIDatePicker!
#IBOutlet weak var timeLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
timePickerView.setValue(UIColor.white, forKeyPath: "textColor")
dateFormat()
// Do any additional setup after loading the view.
}
#IBAction func savePressed(_ sender: UIBarButtonItem) {
let entity = Item(context: context)
entity.time = timeLbl.text
entity.isOn = true
saveData()
self.dismiss(animated: true, completion: nil)
}
#IBAction func cancelPressed(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func valueChanged(sender:UIDatePicker, forEvent event: UIEvent){
dateFormat()
}
func saveData() {
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
func dateFormat() {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeStyle = .short
timeLbl.text = formatter.string(from: timePickerView.date)
}
}
viewcontroller
in this class I am able to fetch and show the core data but don't know how to save the state of the cell switch button and update the data model as there is no use of 'didSelectRowAt' function
tableview class :-
class TableViewController: UITableViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var items = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
print(arr)
}
override func viewWillAppear(_ animated: Bool) {
getData()
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 items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell
cell.timeLbl.text = items[indexPath.row].time
cell.switchBtn.isOn = items[indexPath.row].isOn
return cell
}
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
items = try context.fetch(Item.fetchRequest())
}catch{
print("failed to get the data")
}
}
}
tableview
in this I am able to print the current state of the switch but cannot access the 'items[indexPath.row]' from the tableview class
cell class :-
class TableViewCell: UITableViewCell {
#IBOutlet weak var timeLbl: UILabel!
#IBOutlet weak var switchBtn: UISwitch!
var alarm = Bool()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func valChange(_ sender: UISwitch) {
if sender.isOn{
switchBtn.isOn = true
}else {
switchBtn.isOn = false
}
}
}
In Swift the most efficient way is a callback closure.
In the cell add a property callback with a closure passing a Bool value and no return value. Call the callback when the value of the switch changed.
class TableViewCell: UITableViewCell {
#IBOutlet weak var timeLbl: UILabel!
#IBOutlet weak var switchBtn: UISwitch!
var alarm = Bool()
var callback : ((Bool) -> Void)?
#IBAction func valChange(_ sender: UISwitch) {
callback?(sender.isOn)
}
}
In cellForRow in the controller add the callback, in the closure update the model.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell
let item = items[indexPath.row]
cell.timeLbl.text = item.time
cell.switchBtn.isOn = item.isOn
cell.callback = { newValue in
self.items[indexPath.row].isOn = newValue
}
return cell
}
If cells can be inserted, deleted or moved you have to pass also the cell to get the actual index path
class TableViewCell: UITableViewCell {
#IBOutlet weak var timeLbl: UILabel!
#IBOutlet weak var switchBtn: UISwitch!
var alarm = Bool()
var callback : ((UITableViewCell, Bool) -> Void)?
#IBAction func valChange(_ sender: UISwitch) {
callback?(self, sender.isOn)
}
}
and
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell
let item = items[indexPath.row]
cell.timeLbl.text = item.time
cell.switchBtn.isOn = item.isOn
cell.callback = { currentCell, newValue in
let currentIndexPath = tableView.indexPath(for: currentCell)!
self.items[currentIndexPath.row].isOn = newValue
}
return cell
}