How to call Dictionary values in tableView..
Getting error
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet var tblView: UITableView!
var AnimalName = ["e":["Elephant","EEE"","l":["Lion","LL"],h":["Horse",huh"]]
var initial = Array(AnimalName.alKeys) //error in this line
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return AnimalName.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = AnimalName[indexPath.row] //how to call the cell
return cell
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return initial // not getting output
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return index // How to select
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet var tblView: UITableView!
var AnimalName = ["e":["Elephant","EEE"], "l":["Lion","LL"], "h":["Horse", "huh"]]
var initial: [String] = [] //error in this line
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.initial.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let animalsOfSection = self.AnimalName[self.initial[section]] {
return animalsOfSection.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
if let animal = self.AnimalName[self.initial[indexPath.section]]?[indexPath.row] {
cell.textLabel?.text = animal //how to call the cell
}
return cell
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return self.initial // not getting output
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
if let index = self.initial.indexOf(title) {
return index // How to select
}
return 0
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.initial = Array(self.AnimalName.keys).sort(<)
}
}
["Horse",huh"] should be ["Horse","huh"]
"EEE"" should be "EEE"]
"LL"],h" should be "LL"],"h"
var initial = Array(AnimalName.alKeys)
should be
var initial = Array(AnimalName.keys)
You shouldn't need SO to find and fix typos. Also, try Ctrl+Space after a period, it will propose the appropriate function names and help you avoid misnaming them.
Related
I am trying to delete a cell in the tableview from another view controller. I have modeled my code similar to the question posted below but I still can't seem to successfully delete the selected row/cell in the CalorieVC when the delete button is pressed in the DeleteVC
Deleting a row of a tableview from another viewcontroller
SideNote: there is button in the cells to popup the DeleteVC, I am also getting an error upon pressing the the deleteBtn in the CalorieVC: DeleteRowInTableviewDelegate on let picked saying Thread 1: Fatal error: Index out of range
import UIKit
class CalorieViewController: UIViewController {
var selectedFood: FoodList! // allows data to be passed into the CalorieVC
var deleteItems: CalorieItem? // passes data to DeleteVC
// allows data to be sepearted into sections
var calorieItems: [CalorieItem] = []
var groupedCalorieItems: [String: [CalorieItem]] = [:]
var dateSectionTitle: [String] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
// Allows data in cells to seperate by section
groupedCalorieItems = Dictionary(grouping: calorieItems, by: {$0.foodList.date})
dateSectionTitle = groupedCalorieItems.map{$0.key}.sorted()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DeleteSegue" {
let vc: DeleteViewController = segue.destination as! DeleteViewController
vc.deleteItems = self.deleteItems
// vc.delegate = self
}
}
}
extension CalorieViewController: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return dateSectionTitle.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let date = dateSectionTitle[section]
return groupedCalorieItems[date]!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let calorieCell = tableView.dequeueReusableCell(withIdentifier: "CalorieCell") as! CalorieCell
let date = dateSectionTitle[indexPath.section]
let caloriesToDisplay = groupedCalorieItems[date]![indexPath.row]
calorieCell.configure(withCalorieItems: caloriesToDisplay.foodList)
return calorieCell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let calorieHeader = tableView.dequeueReusableCell(withIdentifier: "CalorieHeader") as! CalorieHeader
let headerTitle = dateSectionTitle[section]
calorieHeader.dateLbl.text = "Date: \(headerTitle)"
return calorieHeader
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let calorieFooter = tableView.dequeueReusableCell(withIdentifier: "CalorieFooter") as! CalorieFooter
//Cell Total Code
let date = dateSectionTitle[section]
let subtotal = groupedCalorieItems[dispensary]?.map { $0.getCalorieTotal() }.reduce(0, +) ?? 0
calorieFooter.calorieTotal.text = String(subtotal!)
return calorieFooter
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 150
}
}
extension CalorieViewController: DeleteRowInTableviewDelegate {
func deleteRow(inTableview rowToDelete: Int) {
let picked = dateSectionTitle[rowToDelete]
let selectedCell = groupedCalorieItems[dod]
delete(selectedCell)
// calorieItems.remove(at: rowToDelete) // tried using this and I get an error code upon segueing back to the CalorieVC
tableView.reloadData()
}
}
import UIKit
protocol DeleteRowInTableviewDelegate: NSObjectProtocol {
func deleteRow(inTableview rowToDelete: Int)
}
class DeleteViewController: UIViewController {
var modifyItems: CartItem!
var delegate: DeleteRowInTableviewDelegate?
#IBOutlet weak var deleteLbl: UILabel!
#IBOutlet weak var deleteBtn: UIButton!
#IBOutlet weak var cancelBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if isMovingFromParent {
delegate!.deleteRow(inTableview: 1)
}
deleteLbl.text = "Are you sure you want to delete this Food Item from your calorie List?"
}
#IBAction func decline(_ sender: Any) {
dismiss(animated: true)
delegate!.deleteRow(inTableview: 1)
print("Delete Item")
}
#IBAction func cancel(_ sender: Any) {
dismiss(animated: true)
print("Cancel Delete")
}
}
Remove the value from the dataSource
Remove the table cell
extension CalorieViewController: DeleteRowInTableviewDelegate {
func deleteRow(inTableview rowToDelete: Int) {
if caloriesItems.count > rowToDelete {
calorieItems.remove(at: rowToDelete)
tableView.deleteRows(at: [IndexPath(row: rowToDelete, section: 0)], with: .automatic)
} else {
print("index not present")
}
}
}
Do not call reloadData just to delete one row. This is a bad practice.
Use deleteRows instead.
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var addImage: UIImage!
let animalNames = ["lion","monky","tiger"]
let animalImages = [UIImage(named: "lion"), UIImage(named: "monky"), UIImage(named: "tiger")]
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return animalImages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mycell",for:indexPath) as! ImageWithTableViewCell
cell.image1.image=self.animalImages[indexPath .row]
cell.label1.text=self.animalNames[indexPath .row]
return cell
}
#IBAction func addingImages(_ sender: UIButton) {
//what code I have to write here
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If you want array to mutable declare it as var instead of let. and Create 1 var numberOfRecordtoShow
var animalNames = ["lion","monky","tiger"]
var animalImages = [UIImage(named: "lion"), UIImage(named: "monky"), UIImage(named: "tiger")]
var numberOfRecordtoShow = 1
Increate numberOfRecordtoShow by 1 till array count.
#IBAction func addingImages(_ sender: UIButton) {
if numberOfRecordtoShow > animalNames.count{
return
}
numberOfRecordtoShow = numberOfRecordtoShow + 1
//reload table now
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfRecordtoShow
}
import UIKit
class ViewController: UITableViewController {
var animals = [Animal]()
override func viewDidLoad() {
super.viewDidLoad()
self.animals = [Animal(name: "개"),Animal(name: "강아지"),Animal(name: "고양이"),Animal(name: "멍멍이"),Animal(name: "물어")]
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
var animal = Animal.self
animal = animals[indexPath.row] //1
cell.textLabel?.text = animal.name //2
return cell //3
}
}
I am getting the following errors:
error is cannot assign value of type 'Animal' to type 'Animal Type'
error is instance member 'name' cannot be used on type 'Animal
unexpected non-void return value in void function
In your code above, "didSelectRowAtIndexPath" is called after you select certain cell, and it does not return anything. Instead, if you want to display the cell, use "cellForRowAtIndexPath".
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class ViewController: UIViewController {
var animals = [Animal]()
override func viewDidLoad() {
super.viewDidLoad()
self.animals = [Animal(name: "개"),Animal(name: "강아지"),Animal(name: "고양이"),Animal(name: "멍멍이"),Animal(name: "물어")]
}
}
extension ViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// This would works on your table view
var animal = animals[indexPath.row]
cell.textLabel?.text = animal.name
return cell
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var Table1: UITableView!
#IBOutlet var Table2: UITableView!
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
}
In every function of the delegates, you have a tableview argument. You can check here which table it is like this
if tableview == self.Table1
{
//Your code goes here
}
else if tableview == self.Table2
{
//Your code goes here
}
Error-
Missing return function expected in UITableView
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tbl1: UITableView!
#IBOutlet var tbl2: UITableView!
var tblArry1 = ["Namrata","Shweta","Shraddha"]
var tblArry2 = ["Shahade","Shirbhate","Deshmukh"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if tableView == self.tbl1
{
return 1
}
else if tableView == self.tbl2
{
return 1
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tbl1
{
return tblArry1.count
}
else if tableView == self.tbl2
{
return tblArry2.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView
if tableView == self.tbl1
{
var cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath)
cell.textLabel?.text = tblArry1[indexPath.row]
return cell
} else if tableView == self.tbl2 {
var cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath)
cell.textLabel?.text = tblArry2[indexPath.row]
return cell
}
}
How to call method
internal func segconChanged(segcon: UISegmentedControl, var text:String){
switch segcon.selectedSegmentIndex {
case 0:
print("whoo")
return text = "clicked Trainings"
case 1:
print("yeahh")
return text = "clicked Daily"
default:
break
}
}
from
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
?
I am beginner of swift.
I am using UISegmentedControl, and UITableView.
When I click UISegmentedControl, make it change to UITableViewCell.
Please look at inside of func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
I added segconChanged(UISegmentedControl(), text: "") to call method,
but I think this is wrong and actually doesnt work.
Please give me advice.
This is all code.
import UIKit
class TrainingLogViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var myTableView: UITableView!
#IBOutlet weak var segment: UISegmentedControl!
let tabLog: NSArray = ["Trainings", "Daily"]
override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
myTableView.dataSource = self
segment.addTarget(self, action: "segconChanged:", forControlEvents: UIControlEvents.ValueChanged)
}
var text: String = ""
internal func segconChanged(segcon: UISegmentedControl, var text:String){
switch segcon.selectedSegmentIndex {
case 0:
print("whoo")
return text = "clicked Trainings"
case 1:
print("yeahh")
return text = "clicked Daily"
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 10
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let text: String = ""
*segconChanged(UISegmentedControl(), text: "")
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "LogTraining")
cell.textLabel?.text = text
cell.detailTextLabel?.text = "subtitle"
return cell
}
}
You dont need to call segconChanged() function manually as it will automatically be called when segment is changed. So just reload your tableview when segment is changed, check its index and populate data acccordingly i.e. in cellForRowAtIndexPath method.
Try this code :
import UIKit
class TrainingLogViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var myTableView: UITableView!
#IBOutlet weak var segment: UISegmentedControl!
let tabLog: NSArray = ["Trainings", "Daily"]
override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
myTableView.dataSource = self
segment.addTarget(self, action: "segconChanged:", forControlEvents: UIControlEvents.ValueChanged)
}
func segconChanged(segcon: UISegmentedControl){
self.myTableView.reloadData()
switch segcon.selectedSegmentIndex {
case 0:
print("clicked Trainings")
case 1:
print("clicked Daily")
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("LogTraining", forIndexPath: indexPath)
cell.textLabel?.text = (self.segment.selectedSegmentIndex == 0) ? tabLog[0] : tabLog[1]
cell.detailTextLabel?.text = "subtitle"
return cell
}
}