How can I display multiple string values to multiple labels in a custom TableView Cell in swift ios? - ios

var leadername = ["1","2","3","4"]
var districts = ["Delhi","Kerala"]
override func viewDidLoad() {
leadTableSetup()
super.viewDidLoad()
}
func leadTableSetup(){
LeadTableView.delegate = self
LeadTableView.dataSource = self
self.LeadTableView.register(UINib(nibName: "LeaderBoardTableViewCell", bundle: nil), forCellReuseIdentifier: "leadCell")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 14
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "leadCell") as! LeaderBoardTableViewCell
// Set text from the data model
cell.areaLbl.text = districts[indexPath.row]
cell.leaderNameLbl.text = leadername[indexPath.row]
return cell
}
I have declared two strings and I need to display these strings in the labels in my custom collection view cell that I have created. How can I achieve this? I need to display "leadername" string in one label and "districts" label in another label.

Go with this demo, Shared Demo
After the demo, If you still face any problem then let me know.
Now Listen Here
I think you need output something like this,
Follow the steps: -
Create a new viewcontroller(says, CustomTableVC) in your storyboard and one UITableView(give constraints and delegate to its own class), take outlet of UItableView (says, tblMyCustom)
Now press CLT+N for new file and do like this below image, Subclass - UItableViewCell and also tick on XIB option.
Open our xib file, add new UIView (says myView, as you see highted in below image), in this myView add two labels
Now take outlet of these two labels in its customCell class
class CustomTableCell: UITableViewCell {
#IBOutlet var lblLeaderNo: UILabel!
#IBOutlet var lblDistict: 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
}
}
Now back to your Viewcontroller Class
import UIKit
class CustomTableVC: UIViewController , UITableViewDelegate, UITableViewDataSource{
#IBOutlet var tblMyCustom: UITableView!
var leaderno : [String]!
var distict : [String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tblMyCustom.register(UINib(nibName: "CustomTableCell", bundle: nil), forCellReuseIdentifier: "customCell")
self.leaderno = ["1", "2", "3", "4"]
self.distict = ["Delhi","Kerala", "Haryana", "Punjab"]
// above both array must have same count otherwise, label text in null
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return leaderno.count;
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var customCell: CustomTableCell! = tableView.dequeueReusableCell(withIdentifier: "customCell") as? CustomTableCell
customCell.lblLeaderNo.text = self.leaderno[indexPath.row]
customCell.lblDistict.text = self.distict[indexPath.row]
return customCell
}
}
above all is code of VC, it is not getting settle down here in single code format, I dont know why.
Now, follow these steps you get output as i show you image in starting of the procedure.

Related

How do you create a tableView inside a tableViewCell?

I have been searching for some time now and have developed a massive headache trying to solve this problem. Basically, I would like to have a parent tableView mainTableView to contain a tableViewCell that includes a label and another tableView innerTableView. This problem is not as simple as I had hoped.
If there is a better way to implement what I want with different components, please let me know.
Otherwise, I have tried to simplify the code to its bare bones with simple data. Please assume I have correctly connected all my outlets properly. I have 3 swift files for this simplified version. ViewController.swift is the main VC that holds the mainTableView. MainTableViewCell.swift is the main cell that will hold a label and a tableView innerTableView in it. InnerTableViewCell is the final cell that will be associated with the innerTableView. In this cell, there is only a label. I have been successful in creating this first layer and the mainNameLabel.text shows up properly on the main storyboard. However, I have configured MainTableViewCell to the best of my knowledge and have come short to success. The innerTableView does not appear on the main storyboard.
Below, I will provide the code of each swift file:
ViewController.swift
//
// ViewController.swift
// NestedTableViews
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var mainTableView: UITableView!
//fake data
var arr = ["Hello", "Hi", "Whats up", "How's it going"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mainTableView.delegate = self
mainTableView.dataSource = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell") as! MainTableViewCell
let word = arr[indexPath.row]
cell.mainNameLabel.text = word
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
}
MainTableViewCell.swift
//
// MainTableViewCell.swift
// NestedTableViews
//
import UIKit
class MainTableViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var mainNameLabel: UILabel!
#IBOutlet weak var innerTableView: UITableView!
var innerArr = ["How are you?", "How are you doing?", "What's the matter?"]
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
innerTableView.dataSource = self
innerTableView.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InnerTableViewCell") as! InnerTableViewCell
let innerWord = innerArr[indexPath.row]
cell.innerNameLabel.text = innerWord
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return innerArr.count
}
}
InnerTableViewCell
//
// InnerTableViewCell.swift
// NestedTableViews
//
import UIKit
class InnerTableViewCell: UITableViewCell {
#IBOutlet weak var innerNameLabel: 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
}
}
Here is what the storyboard looks like in this current state:
What is it that I am doing wrong? I could ask 100 questions but regardless, I am still very stuck here. How do I get the nested tableView innerTableView to appear and with the proper data?
Thank you in advance

iOS - UITableView inside a UIView

I want to display a UITableView inside a UIViewController. This View Controller contains a UISegmentedControl with two screens (FirstViewControllerand SecondViewController).
The first View Controller is the one that contains the UIViewTable (please don't mind the second).
When I execute the app in the simulator, everything works fine, but when I try to scroll the table view in the first ViewController, the cells disappear. The only way to make them reappear is to kill the app and reopen it again.
I'm new to iOS development (I come from Android), and I'm obviously missing something here.
I already tried adding a UIViewTable outside a container UIView and it works fine. So I'm guessing the problem has to do with the container or the segmented control...
Here's my implementation:
Storyboard
UIViewController with UISegmentedControl and UIView (which will contain the two screens of the segmented control).
View Controller
#IBOutlet weak var container: UIView!
var sectionViews:[UIView]!
override func viewDidLoad() {
super.viewDidLoad()
sectionViews = [UIView]()
sectionViews.append(FirstViewController().view)
sectionViews.append(SecondViewController().view)
for v in sectionViews {
container.addSubview(v)
}
container.bringSubviewToFront(sectionViews[0])
}
#IBAction func switchViewsAction(_ sender: UISegmentedControl) {
self.container.bringSubviewToFront(self.sectionViews[sender.selectedSegmentIndex])
}
First View Controller
The FirstViewController has a swift and a xib files, and has two files Cell.swift and Cell.xib for the table cell.
FirstViewController.swift
#IBOutlet weak var tableView: UITableView!
let cellID = "CellId"
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: cellID)
self.tableView.dataSource = self
self.tableView.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! Cell
cell.label.text = "\(indexPath.row)"
return cell
}
FirstViewController.xib
Cell.xib
Any help will be appreciated!
Thanks
One obvious problem is that you are saying container.addSubview(v) without giving v any frame or constraints. Since you use autolayout to position container, you ought to use autolayout to position v as well. You should set its top, bottom, leading, and trailing anchors to equal those of container with a constant of zero. (And set its translates... to false.) Do that for both cases of v in the loop.
However, there is much more serious problem, which is that the view controllers that you create by saying FirstViewController() and SecondViewController() are not retained. Therefore they vanish in a puff of smoke. They thus lose their functionality; for example, the table view no longer has any data source or delegate so it has no cells.
What you are doing is totally illegal. You cannot simply use a view controller to "dumpster-dive" as a way of grabbing its view and shove its view, willy-nilly, into the interface. You must make the view controller a child view controller of your parent view controller (Item in this case). There is an elaborate dance you must do in order to ensure that the child view controller has its proper place in the view controller hierarchy and receives in good order all the messages that a view controller must receive, and you are not doing the dance.
For examples of how to do the dance, see for instance my answers
https://stackoverflow.com/a/41898819/341994
and
https://stackoverflow.com/a/52666843/341994
import UIKit
class TestViewController: UIViewController , UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak var segmentControlOutlet: UISegmentedControl!
#IBOutlet weak var tableView: UITableView!
var arrayName = ["Label1", "Label2", "Label3","Label4","Label5","Label6","Label7","Label8","Label9","Label10"]
var arrayName2 = ["Label1", "Label2", "Label3","Label4","Label5"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func segmentControlAction(_ sender: UISegmentedControl) {
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if segmentControlOutlet.selectedSegmentIndex == 0 {
return arrayName.count
}else{
return arrayName2.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TestTableViewCell", for: indexPath) as! TestTableViewCell
if segmentControlOutlet.selectedSegmentIndex == 0 {
cell.textLabel?.text = arrayName[indexPath.row]
}else{
cell.textLabel?.text = arrayName2[indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
And this code is for UITableViewCell Class:-
import UIKit
class TestTableViewCell: UITableViewCell {
#IBOutlet weak var labelName: 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
}
}

Label not appearing in Swift table

No data is appearing in my Swift table. I'm fairly new to Swift and not quite sure why this or what I might be missing. I followed the guide here for the most part with some differences:
Apple Table Creation
Here's the tableView definition:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "AccountTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AccountTableViewCell else {
fatalError("The dequeued cell is not an instance of AccountTableViewCell.")
}
let item = userDataSource[indexPath.row]
// Dummy values just to test this out
cell.leftLabel.text = "test1";
cell.rightLabel.text = "test2";
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->Int {
return userDataSource.count;
// This should be an array value, but I have also tried passing a static int here as well to test
}
Here is my class definition with the implemented procotols:
class AccountViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
And here is my table cell definition:
class AccountTableViewCell: UITableViewCell {
//MARK: Properties
#IBOutlet weak var leftLabel: UILabel!
#IBOutlet weak var rightLabel: 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
}
}
I've got both rightLabel and leftLabel setup in the Storyboard.
I can go to the account page represented by this view controller and a table display does come up - it just has absolutely no data in it.
What am I missing?
It is not sufficient to simply add a UITableView to your view controller scene. You must set the tableview's dataSource property to your view controller instance in the Storyboard connections inspector for the tableview.

UITableView always displays basic cell instead of custom cell in Swift

I spent hours of trying to fix this, but my simple app still displays the basic cell type instead of my prototype cell. I'm aware of using the identifier and registering after loading up the view, but it still displays the basic cells with just one label.
Here is my code so far:
My prototype is using this UITableViewCell:
class CoinTableViewCell: UITableViewCell {
#IBOutlet weak var coinIcon: UIImageView!
#IBOutlet weak var coinTitleLabel: UILabel!
#IBOutlet weak var holdings: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
UITableViewController:
class CoinTableViewController: UITableViewController {
var coins = ["Coin1","Coin2","Coin3"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(CoinTableViewCell.self, forCellReuseIdentifier: "currency_cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return coins.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:CoinTableViewCell! = self.tableView.dequeueReusableCell(withIdentifier: "currency_cell", for: indexPath) as! CoinTableViewCell
let coinName = coins[indexPath.row]
cell.coinTitleLabel?.text = coinName
return cell!
}
}
I would be so grateful if someone is able the help me out with this!
You are creating your custom cell directly on the tableview in the storyboard, right ?
If this is the case then you don't need to register the cell in your viewDidLoad as the storyboard takes care of that. You just deque it and it's good to go.
If you register it manually you just override what the storyboard did and end up getting a regular cell as the cell gets instantiated from the code instead of getting instantiated from the storyboard.
Cheers

UITableView doesn't scrolling while scrolling over the cell

I created a UITableView in a UIViewController from the storyboard and create custom tableViewCell class. Now when I run my project,
It is not scrolling when I touch any cell and move up/down.
BUT, it scrolls if I start scrolling with the either end of UItableViewCell (nearly, 15px of left inset).
I tried to create another fresh tableView, still not working.
I tried to create a tableViewController, still not working.
Then I think the code is NOT the cause of the issue.
Using Xcode 8.2.1
Below is my code work :
Class File
struct Quote {
var text: String
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView?
let cellIdentifier = "cell"
// Array of strings for the tableView
var tableData = [Quote(text: "zadz ad azd azds fsd gdsfsd"), Quote(text: "zakd gqsl jdwld bslf bs ldgis uqh dm sd gsql id hsqdl sgqhmd osq bd zao mos qd"), Quote(text: "azdhsqdl sb ljd ghdlsq h ij dgsqlim dhsqihdùa dbz ai ljsm oqjdvl isq dbvksqjld"), Quote(text: "dsqb jhd gs qdgsq dgsq u hdgs qli hd gsql i dgsq li dhs qij dhlqs dqsdsd.")]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return number of rows in table
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create Resusable Cell, get row string from tableData
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier)! as! cellClass
let row = indexPath.row
// Set the labels in the custom cell
cell.mainText.text = tableData[row].text
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Do what you want here
let selectValue = self.tableData[indexPath.row]
print("You selected row \(indexPath.row) and the string is \(selectValue)")
}
}
And this is my cellClass: (Custom cell)
class cellClass: UITableViewCell {
#IBOutlet weak var mainText: 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
}
}
Storyboard hierarchy of UITableView
You might be have some x-code issues because generally it never happens and I run your project it working properly as usually it works.
Below is code work I have done.
I'm not taking sturcture of array like you, I'm just doing with taking simple array.
my array is
arrayData = ["One", "Two", "three", "four"]
below is cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : cellClass = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cellClass
cell.lblstates.text = arrayData[indexPath.row]
return cell
}
If you facing any issue then let me know.
Check if the user interaction Enabled check of your cell is off or not in the storyboard
Resolved: I had to uninstall and install Xcode again..

Resources