I am loading data into a UITableView. The first load happens properly for the first 10 cells in
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
the indexPath.row increments properly and loads the data into the proper cells from the data source. I then implemented a load more when the bottom of the table is reached. Now func tableView is called but it is stuck at indexPath.row = 9. I have implemented a checker in
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
And it appears that the proper number of rows has been added.
Edit: I having issue with the my second uitableview (there are two in this scene) The checker is a print statement that is called and returns the proper uitableView and this happens before the tableView gets stuck at the same value.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.table {
return users2.count
}
else {
print("married barry", tableFeedCount)
return tableFeedCount
}
}
Try following:
Declare boolean
let boolNotMoreData : Bool = true
Append new data to your data source
let arrResponse: [Any]? = (responseObject["news"] as? [Any])
if arrResponse?.count == 0{
boolNotMoreData = false;
}
for dictResponse in arrResponse as! [[String: Any]] {
self.arrDataSource.append(NewsClass(responseDict: dictResponse))
}
self.tblViewNews?.reloadData()
Now fetch new data
private func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == arrNews.count - 1 {
if boolNotMoreData {
currentPage += 1
getYourData()
}
}
}
This worked Successfully
#IBOutlet weak var Submitted: UITableView!
#IBOutlet weak var ViewAssigenment: UITableView!
var Arrayone:[String] = []
var ArrayTwo:[String] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
var count:Int?
if tableView == self.ViewAssigenment
{
count = Arrayone.count
}
else if tableView == self.Submitted
{
count = ArrayTwo.count
}
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if tableView == self.ViewAssigenment
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ViewCell") as!
ViewAssigenmentTableViewCell
let obj =Arrayone[indexPath.row]
cell.lblTitle.text = obj.AssTitle
return cell
}
else
{
let cell1 = tableView.dequeueReusableCell(withIdentifier: "Submittcell") as! SubmittedAssigenmentTableViewCell
let obj2 = ArrayTwo[indexPath.row]
cell1.lbltitle.text = obj2.AssTitle
return cell1
}
}
Related
I am trying to use a dictionary for a tableView datasource, I am getting an object back from the database that contains a key and an array of values, so a [String: [String]]
var requestedList = [String]()
var keyArr = [String]()
var requestedDictionary = [String: [String]]()
let tQuery = PFQuery(className: "MyClass")
tQuery.whereKey("username", equalTo: PFUser.current()?.username as Any)
tQuery.selectKeys(["descContent", "header"])
do {
let returnedObjects = try tQuery.findObjects()
for object in returnedObjects {
let header = object["header"] as! String
keyArr.append(header)
if let arr = object["descContent"] as! [String]? {
requestedDictionary[header] = arr
requestedList += arr
}
}
} catch {
}
I can't seem to correspond the values correctly to the rows of the tableView however, I was suggested to use an array to store the values which is what I have done with the keyArr. My problem is how do I access the contents of the keys and the corresponding values in the datasource methods?? This is what I have so far but I haven't been able to link the keys and values accordingly
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return requestedList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RequestViewCell", for: indexPath) as! RequestViewCell
cell.descLbl.text = "Your ticket has been requested by \(requestedList[indexPath.row])"
cell.refLbl.text = "for: \(keyArr[indexPath.row])"
cell.leftBtn.tag = (indexPath.section * 100) + indexPath.row
cell.leftBtn.addTarget(self, action: #selector(leftClick(sender:)), for: .touchUpInside)
cell.rightBtn.tag = (indexPath.section * 100) + indexPath.row
cell.rightBtn.addTarget(self, action: #selector(rightClick(sender:)), for: .touchUpInside)
return cell
}
You can turn dictionary into tableView representable data this way.
let requestedDictionary:[String: [String]] = [
"Key-1":["Value-1","Value-2","Value-3","Value-4"],
"Key-A":["Value-X","Value-Y","Value-Z"],
"Key-a":["Value-x","Value-y"],
]
lazy var data:[(key:String,values:[String])] = requestedDictionary.compactMap({(key:$0,values:$1)})
func numberOfSections(in tableView: UITableView) -> Int {
data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].values.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = data[indexPath.section].values[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return data[section].key
}
Hope it helps.
What I'm trying to do is separate my cells into sections by their Brand
what Ive been able to do so far is pass data of selected items from HomeVC to populate the cells of the CartVC
I am trying to separate the sections by brand, the brand data is a part of the model Items Class (name, brand, imageUrl, price, & weight) and the Items class retrieves data from CloudFirestore to populate the cells of the HomeVC
How would I be able to to separate the cells into sections by their brand, when passed into the CartVC.
So far what I've done seems to fail, because once I pass an item from the HomeVC to the CartVC I only get one header cell, with the brand name of the first item I passed into the CartVC. When I pass more data into the the CartVC all the cells stay in the section of the first item passed when im trying to section off all my CartCells by their brand
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as? HomeCell else { return UITableViewCell() }
let item = itemSetup[indexPath.row]
cell.configure(withItems: item)
cell.addActionHandler = { (option: Int) in
print("Option selected = \(option)")
self.tray.append(Tray(cart: item))
item.selectedOption = option
}
return cell
}
}
class CartViewController: UIViewController {
var items: ProductList!
var sectionModel: [SectionModel] = []
var tray: [Tray] = []
var groupedItems: [String: [Tray]] = [:]
var brandNames: [String] = []
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
groupedItems = Dictionary(grouping: tray, by: {$0.cart.brand})
brandNames = groupedItems.map{$0.key}.sorted()
}
}
extension CartViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell
let cart = tray[indexPath.row]
cell.configure(withItems: cart.cart)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cartHeader = tableView.dequeueReusableCell(withIdentifier: "CartHeader") as! CartHeader
cartHeader.storeName.text = "Brand: \(tray[section].cart.brand)"
return cartHeader
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
}
class Tray {
var cart: ProductList!
init(cart: ProductList) {
self.cart = cart
}
}
just set your your tableview functions like and you'll have no problem setting things up by section
func numberOfSections(in tableView: UITableView) -> Int {
return brandNames.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let brand = brandNames[section]
return groupedItems[brand]!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cartCell = tableView.dequeueReusableCell(withIdentifier: "CartCell") as! CartCell
let brand = brandNames[indexPath.section]
let itemsToDisplay = groupedItems[brand]![indexPath.row]
cartCell.configure(withItems: itemsToDisplay.cart)
return cartCell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cartHeader = tableView.dequeueReusableCell(withIdentifier: "CartHeader") as! CartHeader
let headerTitle = brandNames[section]
cartHeader.brandName.text = "Brand: \(headerTitle)"
return cartHeader
}
I'm using an array of instances of the same struct to populate a tableview and I'm stumped by the last item in the array displaying in every cell.
class RoutesViewController: UIViewController, UITableViewDataSource {
#IBOutlet weak var routesTableView: UITableView!
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return type1UnownedRoutesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell
for Flight in type1UnownedRoutesArray {
routeCell.originLabel.text = "Origin: \(Flight.origin)"
routeCell.destinationLabel.text = "Destination: \(Flight.destination)"
routeCell.priceLabel.text = "Price: $\(Flight.popularity)"
}
return routeCell
}
And the struct itself:
struct Flight {
var origin: String
var destination: String
var mileage: Int
var popularity: Int
var isOwned: Bool
}
If I add [indexPath.row] after for Flight in type1UnownedRoutesArray I get Type Flight does not conform to protocol Sequence
Thanks in advance for the help.
The source of your issue is this one in your cellForRow method, you are cycling over all your flights objects in your array, and of course the last value is keeping in your cell, so you need replace this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell
for Flight in type1UnownedRoutesArray {
routeCell.originLabel.text = "Origin: \(Flight.origin)"
routeCell.destinationLabel.text = "Destination: \(Flight.destination)"
routeCell.priceLabel.text = "Price: $\(Flight.popularity)"
}
return routeCell
}
By this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell
let flight = type1UnownedRoutesArray[indexPath.row]
routeCell.originLabel.text = "Origin: \(flight.origin)"
routeCell.destinationLabel.text = "Destination: \(flight.destination)"
routeCell.priceLabel.text = "Price: $\(flight.popularity)"
}
Hope this helps
The problem is you should not be iterating your flights array inside the cellforrow method as it is called once per item in your array.
try this instead
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell
let flight = type1UnownedRoutesArray[indexPath.row]
routeCell.originLabel.text = "Origin: \(flight.origin)"
routeCell.destinationLabel.text = "Destination: \(flight.destination)"
routeCell.priceLabel.text = "Price: $\(flight.popularity)"
return routeCell
}
I want to use XMSegmentController(https://cocoapods.org/?q=segmen) to change the different tableview,I do not know what is missing in my program, which leads to a black situation when I run. Does anyone know what to add to my program? Thank you.
Here is mt code:
import UIKit
import XMSegmentedControl
class ViewController: UIViewController, XMSegmentedControlDelegate,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var segmentedControl1: XMSegmentedControl!
#IBOutlet weak var tableview1: UITableView!
#IBOutlet weak var tableview2: UITableView!
let one = ["1","2","3"]
let two = ["4","5","6"]
override func viewDidLoad() {
super.viewDidLoad()
segmentedControl1.delegate = self
segmentedControl1.segmentTitle = ["One", "Two"]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "left", for: indexPath)
cell.textLabel?.text = one[indexPath.row]
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "right", for: indexPath)
cell.textLabel?.text = two[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableview1 {
return one.count
}
return two.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func xmSegmentedControl(_ xmSegmentedControl: XMSegmentedControl, selectedSegment: Int) {
if xmSegmentedControl == segmentedControl1 {
print("SegmentedControl1 Selected Segment: \(selectedSegment)")
}
}
}
Set your controller as initial ViewController to show your Controller. Now use selectedSegment argument from delegate method and hide/show the tableView according to it.
func xmSegmentedControl(_ xmSegmentedControl: XMSegmentedControl, selectedSegment: Int) {
if xmSegmentedControl == segmentedControl1 {
tableview1.isHidden = selectedSegment != 0
tableview2.isHidden = selectedSegment != 1
}
}
Also instead of using two tableView you can use single tableView like this.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if segmentedControl1.selectedSegment == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "left", for: indexPath)
cell.textLabel?.text = one[indexPath.row]
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "right", for: indexPath)
cell.textLabel?.text = two[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if segmentedControl1.selectedSegment == 0 {
return one.count
}
return two.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
And in delegate method of xmSegmentedControl simply reload the tableView.
func xmSegmentedControl(_ xmSegmentedControl: XMSegmentedControl, selectedSegment: Int) {
if xmSegmentedControl == segmentedControl1 {
tableView.reloadData()
}
}
what is your initial ViewController?can you please check in your storyboard?
set an initial viewcontroller.
func xmSegmentedControl(_ xmSegmentedControl: XMSegmentedControl, selectedSegment: Int) {
if xmSegmentedControl == segmentedControl1 {
tableviewOne.isHidden = selectedSegment != 0
tableviewSecond.isHidden = selectedSegment != 1
}
}
I have a tableView on mainStoryboard with two custom cells.
I would like to set two more cells at different row.
However When I implemented the code the added cells replaces original cells. (Custom cell of "Basic grammar3" and "Basic grammar5" are disappearing.)
I was trying to find the answer but could not find out.
I have image and code added below.
import UIKit
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tblStoryList: UITableView!
var array = PLIST.shared.mainArray
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.array.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 || indexPath.row == 3 || indexPath.row == 5 {
let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell", for: indexPath) as! HeaderCell
cell.headerTitle.text = indexPath.row == 0 ? "First Stage" : indexPath.row == 3 ? "Second Stage" : "Third Stage"
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "StoryTableviewCell", for: indexPath) as! StoryTableviewCell
//making plist file
let dict = self.array[indexPath.row - 1]
let title = dict["title"] as! String
let imageName = dict["image"] as! String
let temp = dict["phrases"] as! [String:Any]
let arr = temp["array"] as! [[String:Any]]
let detail = "progress \(arr.count)/\(arr.count)"
//property to plist file ăă€ăȘă
cell.imgIcon.image = UIImage.init(named: imageName)
cell.lblTitle.text = title
cell.lblSubtitle.text = detail
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
return
}
tableView.deselectRow(at: indexPath as IndexPath, animated:true)
if indexPath.row == 3 {
return
}
tableView.deselectRow(at: indexPath as IndexPath, animated:true)
if indexPath.row == 5 {
return
}
tableView.deselectRow(at: indexPath as IndexPath, animated:true)
let messagesVc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
messagesVc.object = self.array[indexPath.row - 1]
self.navigationController?.show(messagesVc, sender: self)
}
You could use sections for your table view. Now, you are returning 1 in your numberOfSections function. And it is creating only one section. If you want to use headers, you can use sections for your need. And also you can fill your table view cells with multidimendional arrays. For example:
For adjusting your section headers:
let lessonTitles = ["First Stage", "Second Stage"]
Titles for sections:
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < lessonTitles.count {
return lessonTitles [section]
}
return nil
}
For adjusting your sections and rows:
let lessons = [["Basic Grammar 1", "Basic Grammar 2"], ["Basic Grammar 3", "Basic Grammar 4"]]
Number of sections function should be:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return lessons.count
}
Number of rows in section should be:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lessons[section].count
}
And creating your cells is like this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellText = data[indexPath.section][indexPath.row]
...
}
Try like this...
func numberOfSections(in tableView: UITableView) -> Int
{
return numberOfStages
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return numberOfRowsInCurrentStage
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
return customizedCell
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat
{
return requiredHeight
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView?
{
return stageCountView
}
You can use viewForHeaderInSection if you want to show stage count on top.
edit: The comment by raki is the much better solution (use headers). I leave this here in case you want something closer to your existing implementation.
You have to change your numbering scheme in order to insert these additional rows (and not replace existing rows). So you might want to adjust the row for the "normal" elements like this:
func adjustRow(_ row: Int) -> Int {
if row < 3 {
return row
} else if row < 5 {
return row+1
} else {
return row+2
}
}