Implement a dynamic table within a static table view (cell) - ios

So basically I have implemented a static table so far and at the very bottom, I want to add another dynamic table for the participant list of the event. Check out the screenshot here:
My problem now is, that I'm not able to setup the dynamic table with its own class which is placed in the last static table view cell. You can check out the red marked squares in the screenshot. My actual plan was to give the dynamic table its own class and then retrieve the participant list as an array and setup the numberOfRowsInSection according to the count of the array etc.
Do you guys have an idea how I can implement that within a static table? Basically, how can I add that dynamic table at the bottom, including later then endless scrolling?
I've tried this post so far but it didn't completely help me: Dynamic UITableView inside static cell
I'll add my solution below.
Your help would appreciated a lot!
Kind regards
Matt

Unless there's a real reason to have the top portion be a table as well, the easiest solution is going to be to make the top portion a table header view and just use a dynamic table.

Create a ViewController. Then place two ContainerViewControllers inside of the ViewController. Create segues to 2 separate tableViewcontrollers using embed. One to the static tableview and one to the dynamic tableview. This way you could have a static table on top and a dynamic one below.

Okay thank you rMickeyD for your tip. I used it partially and implemented it. You can see the result on this screenshot here:
Adding to this I set the height of the cell in the static table with a prepareToSegue to the array of the guests.count * 44 for the cell height in the right.
Code for the static table view (left):
import UIKit
class EventDetailTableViewController: UITableViewController {
var attendeesArrayFromDatabase = ["Kathi", "Cansin", "Tyrone", "Manuel", "Stavros", "Christoph", "Maria", "Aditya", "Kathi", "Cansin", "Tyrone", "Manuel", "Stavros", "Christoph", "Maria", "Aditya"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 1 && indexPath.row == 0 {
let height:CGFloat = CGFloat(attendeesArrayFromDatabase.count * 44)
return height
}
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destViewController : EventPeopleJoinedContainerTableViewController = segue.destinationViewController as! EventPeopleJoinedContainerTableViewController
destViewController.attendeesArray = attendeesArrayFromDatabase
}
}
and the right tableview for the dynamic table:
import UIKit
class EventPeopleJoinedContainerTableViewController: UITableViewController {
var attendeesArray = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return attendeesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("personJoined", forIndexPath: indexPath) as UITableViewCell
//Create a label with the name of a person from array attendeesArray
let attendeeNameLabel = UILabel(frame: CGRect(x: 70, y: 0, width: cell.frame.width, height: cell.frame.height))
attendeeNameLabel.font = cell.textLabel?.font.fontWithSize(14.0)
attendeeNameLabel.textColor = UIColor.darkGrayColor()
attendeeNameLabel.text = attendeesArray[indexPath.row] as? String
//Create a image view for the profile picture of the guest
let attendeeImageView = UIImageView(frame: CGRect(x: 25, y: 7, width: 30, height: 30))
attendeeImageView.layer.cornerRadius = attendeeImageView.frame.size.width/2
attendeeImageView.layer.borderColor = UIColor.whiteColor().CGColor
attendeeImageView.layer.borderWidth = 0.5
attendeeImageView.clipsToBounds = true
attendeeImageView.image = UIImage(named: "profilPicDummy")
cell.contentView.addSubview(attendeeNameLabel)
cell.contentView.addSubview(attendeeImageView)
return cell
}
}

Related

How To Add Multiple Buttons To UITableViewCells Swift

I am creating a simple iOS app with Xcode and Swift 5 where the user can pick a theme and then the background will change color. I want to accomplish this by adding buttons onto a table view's cells. I know how to add one button to a table view, but I have no idea how to put multiple buttons into a table view cell.
Here is a table view cell with a button I added to it:
p.s.: ignore the text inside of the button
What I'd want is for one button on each side and one in the middle, like this:
Here's my tableviewcontroller:
import UIKit
#objcMembers class TBController: UITableViewController {
var times = 0
var lastChar = ""
var subString = ""
var text = ""
override func viewDidLoad() {
super.viewDidLoad()
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
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 {
return singleton.count
}
// 3
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var cellButton: UIButton!
///////////////////
cellButton = UIButton(frame: CGRect(x: 5, y: 5, width: 50, height: 30))//5, 5, 50, 30
times = times + 1
cell.textLabel?.text = SingletonViewController.singleton[indexPath.row]
if times == 1{
cellButton.setTitle("Back", for: UIControl.State.normal)
cell.addSubview(cellButton)
cell.accessoryView = cellButton
cellButton.backgroundColor = UIColor.blue
cell.tag = 1
}else{
cell.tag = 2
}
return cell
}
}
You need to subclass UITableViewCell and create your own custom implementation, you can do this by code or by IB
This is the IB way of doing it:
When you create a new Cocoa Touch Class file, choose to subclass from UITableViewCell and select the create XIB file option. After that configure the XIB's view whoever you want and set a reuse identifier in the Identity Inspector.
If you want to have the layout from your screenshot, drag a UIStackView, set it's constraints to top, bottom, leading and trailing to the contentView of the cell, set the alignment to horizontal, then select fill equally and drag 3 UIButtons inside of it, the stackView will make sure to arrange them nicely
In your viewController don't forget to register the cell with the tableView, and then return that cell from cellForRowAtIndexPath

Table View data appears on tableview with row selection code

I guess this could be one of my rookie mistakes I couldn't figure out.
I have an app which has a table view. It has text label and detail text label.
When I select a row, I takes me to another story board using segue...all of this works fine except the table view display on my simulator.
detail text label shows up on the simulator shown in this picture circled.
Here is the code I am using to detect cell/row selected. When I comment it out this issue goes away...
What you see in the red circle is gradeselected which is also in the detail text label in the tableview.
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
let gradeselected = String(describing: sgrade)
return [gradeselected]
}
Screenshot of simulator with the issue
Please help in resolving this issue. Let me know if you need any more info.
Xcode 9.1
Swift 4
#Caleb here is my code.
import UIKit
class StudentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var cellButton: UIButton!
#IBOutlet weak var studentDetailTable: UITableView!
var sname:[String]?
var sgrade:[Int]?
var gradetext = "Grade:"
var sstudentname = ""
override func viewDidLoad() {
super.viewDidLoad()
studentDetailTable.delegate = self
studentDetailTable.dataSource = self
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sname!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = studentDetailTable.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = sname[indexPath.row] + gradetext + String(sgrade[indexPath.row])
sstudentname = sname![indexPath.row]
cell?.detailTextLabel?.text = String(sgrade![indexPath.row])
cell?.layer.cornerRadius = (cell?.frame.height)!/2
cell?.backgroundColor = UIColor.blue
cell?.textLabel?.textColor = UIColor.white
cell?.layer.borderWidth = 6.0
cell?.layer.cornerRadius = 15
cell?.layer.borderColor = UIColor.white.cgColor
cell?.textLabel?.textColor = UIColor.white
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedIndex = tableView.dataSource?.sectionIndexTitles!(for: studentDetailTable)
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRow(at: indexPath!)!
let scell = currentCell.detailTextLabel!.text!
sstudentname = (currentCell.textLabel?.text)!
}
// - If I comment this section of the code issue goes away.
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
let gradeselected = String(describing: sgrade)
return [gradeselected]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let myKLVC = segue.destination as! KindergartenLevelViewController
myKLVC.klvstudentname = sstudentname
}
The text in the red circle says [1, 2], which looks like the array that probably holds all the grades, not just the one for a specific cell that we see in the string gradeselected. If you have such an array in your code, look for places where you might be converting it to a string and drawing it. Maybe you did that in an earlier iteration of your code to make sure that the array contained what you thought, or something?
Arrays don't just mysteriously draw themselves on the screen — somewhere, there's some code that causes that to happen. We can't really help you find it because you haven't shown very much of your code, but just knowing what to look for may help you find it yourself.
You can query the selected row via table view's property indexPathForSelectedRow.
The method you have implemented does exactly what you see in the simulator.
Just have a look at the documentation:
property indexPathForSelectedRow: https://developer.apple.com/documentation/uikit/uitableview/1615000-indexpathforselectedrow
func sectionIndexTitles: https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614857-sectionindextitles

UITableViewHeaderFooterView not showing customisations when first loaded

With Swift 3, I am using a subclass of UITableViewHeaderFooterView (called HeaderView) for the header sections on my TableView.
After dequeueing HeaderView, I customise it by
(1) setting the textLabel.textColor = UIColor.red, and (2) adding a subview to it.
When the application first loads, the table view loads up the headers but they have (what I assume is) the 'default' view (with textLabel.textColor being grey, and without my added subview). When I start scrolling and it starts dequeueing more HeaderViews, then the HeaderViews start coming up correctly, until there are eventually no more 'default' formatted HeaderViews.
Subsequent loads of the app no longer shows the 'default' view.
Alternatives considered
I know that this could be done by making my HeaderView a subclass of
UITableViewCell and customising it from the Storyboard, but that
seems like more of a workaround to use a prototype cell when there is
a UITableViewHeaderFooterView class that was designated for headers
Similarly it could be done with a XIB file, but even in Xcode 8 when
creating a subclass of UITableViewHeaderFooterView it doesn't allow
you to create an XIB file (so there must be some reason..)
Any comments/answers explaining why this is happening and how to resolve it are really appreciated!
UPDATE
As requested I've added in the code to show what I've done- you can recreate the problem with the code below and the usual setting up a TableViewController in the Storyboard (Swift 3, Xcode 8.2, Simulating on iOS 10.2 for iPhone 7)
ListTableViewController.swift
import UIKit
class ListTableViewController: UITableViewController {
// List of titles for each header
var titles: [String] {
var titles = [String]()
for i in 1...100 {
titles.append("List \(i)")
}
return titles as [String]
}
// Register view for header in here
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(ListHeaderView.self, forHeaderFooterViewReuseIdentifier: "Header")
}
// Table view data source
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let dequeuedCell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header")
if let cell = dequeuedCell as? ListHeaderView {
cell.title = titles[section]
}
return dequeuedCell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func numberOfSections(in tableView: UITableView) -> Int {
return titles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
}
ListHeaderView.swift
import UIKit
class ListHeaderView: UITableViewHeaderFooterView {
var title: String? {
didSet {
updateUI()
}
}
private func updateUI() {
textLabel?.textColor = UIColor.red
textLabel?.text = title!
let separatorFrame = CGRect(x: 0, y: frame.height-1, width: frame.width, height: 0.25)
let separator = UIView(frame: separatorFrame)
separator.backgroundColor = UIColor.red
contentView.addSubview(separator)
}
}
Here is a screen shot of when the grey headers (screen is full of them upon initial load) and the customised red headers which start to appear upon scrolling.
For anyone interested, seems like this is a bug for which the best solution at this stage is to configure properties such as textColor on the header view in the tableView delegate method willDisplayHeaderView. Doing so 'last minute' just before the view appears allows you to override whatever configurations the system tries to force on the font etc.
Credit to answer found here
Troubles with changing the font size in UITableViewHeaderFooterView
Use this below code
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let dequeuedCell : ListHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header") as? ListHeaderView
cell.title = titles[section]
cell.tittle.textcolor = uicolor.red
return dequeuedCell
}

how to change the data of UItableview?

I have a main menu in my app with 15 item and each item has a sub of 20 items which i also added them as images array (15 image array , some thing like a restaurant menu ) so when ever the user clicks on 1 of the main menu items the app will take him to the sub menu , i have created the main menu table view the issue is with the sub menus do i have to create 15 table view for each sub menu !!??
is there is any way to create 1 table view for the sub menus and change its data according to user click
note : i don't want to use the sections in my table view
any ideas will be much appreciated
Need two viewControllers and a navigationController. One for main menu and other for sub menu. Let them be mainMenuViewController and subMenuViewController. Each controllers contains a tableView.
Create an menuArray containing 15 submenu data.Each submenu is an array.
In didSelectRowAtIndexPath of mainMenuViewController, if user selects a row in the tableView, then pass that data in the menuArray corresponding to the selected row.
For example, if user selects third row,
then pass menuArray[3] to subMenuViewController. Here indexPath.row = 3.
Sample Project Code:
MenuViewController.swift:
import UIKit
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var menuTableView: UITableView!
var imagesArray: NSArray = []
var menuArray: NSArray = []
var subMenuDataArray: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
menuTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
imagesArray = ["soups.jpg","salads.jpg","starters.jpg","pizzas.jpg","burgers.jpeg"]
menuArray = ["Soups","Salads","Starters","Pizzas","Burgers"]
subMenuDataArray = [["Cream of broccoli","Cream of celery","Cream of tomato","Etrog","Gazpacho"],
["Tuna salad","Urnebes","Waldorf salad"],
["Kakori Kebabs","Stir Fried Chilli Chicken"," Microwave Paneer Tikkas","Aloo and Dal ki Tikki","Cheese Balls","Bhuna Masala Chicken Wings"],
["Cheese Pizzas","Chicken Pizzas","Masala Pizzas","Double Cheese Pizzas","Herbal Pizzas"],
["Luger Burger","Le Pigeon Burger","The Company Burger","Dyer’s Deep-Fried Burger","The Lola Burger","Cheeseburger","Raw Steak Tartare Burger","Buckhorn Burger"]]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return imagesArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return 70
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let menuTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let cellImageView: UIImageView = UIImageView.init()
cellImageView.frame = CGRectMake(10, 10, 50, 50)
cellImageView.image = UIImage(named: imagesArray.objectAtIndex(indexPath.row) as! String)
menuTableViewCell.contentView.addSubview(cellImageView)
let menuLabel: UILabel = UILabel.init(frame: CGRectMake(70, 10, 200, 25))
menuLabel.text = menuArray.objectAtIndex(indexPath.row) as? String
menuTableViewCell.contentView.addSubview(menuLabel)
return menuTableViewCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let subMenuViewController: SubMenuViewController = storyboard!.instantiateViewControllerWithIdentifier("SubMenuViewControllerID") as! SubMenuViewController
subMenuViewController.currentSubMenuArray = subMenuDataArray.objectAtIndex(indexPath.row) as! NSArray
navigationController?.pushViewController(subMenuViewController, animated: true)
}
}
SubMenuViewController.swift:
import UIKit
class SubMenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var subMenuTableView: UITableView!
var currentSubMenuArray: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
subMenuTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "subCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return currentSubMenuArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let subMenuTableViewCell = tableView.dequeueReusableCellWithIdentifier("subCell", forIndexPath: indexPath)
let subMenuLabel: UILabel = UILabel.init(frame: CGRectMake(10, 10, 250, 25))
subMenuLabel.text = currentSubMenuArray.objectAtIndex(indexPath.row) as? String
subMenuTableViewCell.contentView.addSubview(subMenuLabel)
return subMenuTableViewCell
}
}
Storyboard:
Output:
To test the sample project, use the following link of my GitHub account:
https://github.com/k-sathireddy/MenuTableViewSample
Declare one array for displaying and change the content of the array according to the selection and screen state like for menu, submenu etc. and reload the table to display the data in the main array. And if you want to display different kind of cell for different selection you can achieve it by taking an enum for whats the current screen state like i said and return required cell initialized in cellForRowAtIndexPath. Its all about how much you can think and implement the logic. Comment below if you need real technical solution with codes you already have used.

How do I link dynamic prototype cells to different UITableViewControllers?

Pardon me but I'm new to code & Swift.
Can't post an image but I need to link my custom UITableViewController 7 dynamic prototype cells to 7 different UItableviewcontrollers. So far I tried to segue the cell to another UITableViewController, but the rest of the cells are linking to the same place as well. Lets say if i want to link a fast food category to a list of fast food restaurants in a UITableViewController, every other category is also linking to the same UITableViewController.
I'm not quite sure what to do.
My main controller code is as follows:
class CategoriesTableViewController: UITableViewController {
var category: [Categories] = categoriesData
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return category.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CategoriesCell", forIndexPath: indexPath)as CategoriesCell
let categories = category[indexPath.row] as Categories
cell.textLabel?.text = categories.category
if let categoryLabel = cell.viewWithTag(100) as? UILabel {
categoryLabel.text = categories.category
}
return cell
}
This is my categories.swift file:
class Categories: NSObject {
var category: String
init(category: String) {
self.category = category
super.init()
}
}
and categories data.swift:
let categoriesData = [Categories(category:"Restaurants/Cafe"), Categories(category:"Fine Dining"), Categories(category:"Catering"),Categories(category:"Buffet"), Categories(category:"Food Court/Hawker Centre"), Categories(category:"Fast Food"), Categories(category:"Others")]
my categories cell.swift shows the following:
class CategoriesCell: UITableViewCell {
#IBOutlet weak var nameLabel: UILabel!
}
Maybe can post pictures so we can see as to why you are going that route.
I think you want the sections of the tableview to display different content?
I would suggest:
split the table view into the number of sections you want (each section can have a given number of rows)
create one UITableViewController class
in your
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
}
Set your content based on section & row number
Try this:
Create 7 different prototype cells.
Change the reuse identifier of each prototype cell to match one of your categories.
Link each prototype cell to a different ViewController with a segue.
In cellForRowAtIndexPath, use the category for that row to fetch the correct prototype cell:
let categories = category[indexPath.row] as Categories
let cell = tableView.dequeueReusableCellWithIdentifier(categories.category, forIndexPath: indexPath) as CategoriesCell

Resources