Cell doesn't show up properly in table view - ios

I'm using TableView to implement it on ViewController. The problem that I'm facing is the number of cells. Currently the cells supposed to return 2 rows but it only show one row.
What I want to achieve
Storyboard - You can ignore the rest of the components except the tableview
import UIKit
class ViewController: UIViewController {
#IBOutlet var locationTableView: UITableView!
let locationArray = ["Current Location", "Where to"]
let picArray = ["currentPic.png", "whereTo.png"]
override func viewDidLoad() {
super.viewDidLoad()
locationTableView.delegate = self
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return locationArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GetLocation", for: indexPath)
let location = locationArray[indexPath.row]
let pic = picArray[indexPath.row]
print(location)
if let locationCell = cell as? GetLocationTableViewCell {
locationCell.locationTitle.text = location
locationCell.iconImage.image = pic
}
return cell
}
}
GetLocationTableViewCell.swift
import UIKit
class GetLocationTableViewCell: UITableViewCell {
#IBOutlet var iconImage: UIImageView!
#IBOutlet var locationTitle: UILabel!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The outcome is really weird
On Simulator
On my iphone
The number of rows differ on both platforms. What did I do wrong? Is it because of constraints?

Here is problem locationArray[indexPath.section] , picArray[indexPath.section] your section is return 0 so you get two times display "Current Location" you need to use indexPath.row
Try this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GetLocation", for: indexPath)
let location = locationArray[indexPath.row]
let pic = picArray[indexPath.row]
print(location)
if let locationCell = cell as? GetLocationTableViewCell {
locationCell.locationTitle.text = location
locationCell.iconImage.image = pic
}
return cell
}

Change your table delegate method like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GetLocation", for: indexPath)
let location = locationArray[indexPath.section]
let pic = picArray[indexPath.row]//replace this line
print(location)
if let locationCell = cell as? GetLocationTableViewCell {
locationCell.locationTitle.text = location
locationCell.iconImage.image = pic
}
return cell
}

You can try like Bellow. You can write array like
let locationArray = [
["textName":"Current Location", "imageName":"currentPic"],
["textName":"Where to", "imageName":"whereTo"]
]
Table view protocol method look like
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 locationArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) CustomCell
cell.textLabel?.text = locationArray[indexPath.row]["textName"]
cell.imageView?.image = UIImage(named: locationArray[indexPath.row]["imageName"]!)
return cell
}

Replace method Following thing in cellRowAtPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GetLocation", for: indexPath)
let location = locationArray[indexPath.row]
let pic = picArray[indexPath.row]
print(location)
if let locationCell = cell as? GetLocationTableViewCell {
locationCell.locationTitle.text = location
locationCell.iconImage.image = pic
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 102 //Give cell height
}

As Per your problem i suggest you to manage constraints that your are applying to tableview and Cell. Here i have provided instruction to follow to get solution. Please Manage to follow same instruction on your project Hope this will solve your problem.
1. Manage tableview constraints
a. Pin your tableview to superview from top,left right
b. Set height constraints of tableview.
c. Make outlet of height constraints for tableview so that we can alter value on runtime.
2. Manage Cell constraints
a. Pin your cell contents to superview from top,left, right,bottom
3. manage tableview constraints on runtime
a. set height constraints of tableview view to content size of table view from cell for tow at index path.
self.tableHeight.constant = self.locationTableView.contentSize.height
Full controller Code.
// Controller.swift
// Copyright © 2017 dip. All rights reserved.
//
import UIKit
class ViewController1: UIViewController {
//1:
//Outlet of tableview Height constraints
#IBOutlet weak var tableHeight: NSLayoutConstraint!
#IBOutlet var locationTableView: UITableView!
let locationArray = ["Current Location", "Where to"]
let picArray = ["currentPic.png", "whereTo.png"]
override func viewDidLoad() {
super.viewDidLoad()
locationTableView.delegate = self
}
}
extension ViewController1: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return locationArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GetLocation", for: indexPath)
let location = locationArray[indexPath.row]
let pic = picArray[indexPath.row]
print(location)
if let locationCell = cell as? GetLocationTableViewCell {
locationCell.locationTitle.text = location
locationCell.iconImage.image = pic
}
//2. set tableivew view height to content Height
self.tableHeight.constant = self.locationTableView.contentSize.height
return cell
}
}
Out Put

Related

Problem with adding tableview into tableview cell swift

I would like to show table view with cell where will be one label and tableview below this label. I have such layout right now:
view above my tables view will be hidden in some conditions so as a result I will have table view on whole screen. So... I found this video where developer managed to solve my task. I did everything similarly to his video but I didn't manage to show table view inside table view cell. Here is my steps:
Added all views to general view.
Attached tags to my table views: 100 for main table view and 90 for inside table view.
Created cell classes and attached them to both cells.
Added extension at main cell like in video.
Handled table view tag in main view controller.
As I see the problem is with inside table view which can't be shown. Below you can see classes for cells. Main cell:
class GeneralCell : UITableViewCell {
#IBOutlet weak var answerOptions: UITableView!
#IBOutlet weak var questionText: UILabel!
}
extension GeneralCell{
func setTableViewDataSourceDelegate <D:UITableViewDelegate & UITableViewDataSource> (_ dataSourceDelegate: D, forRow row: Int)
{
answerOptions.delegate = dataSourceDelegate
answerOptions.dataSource = dataSourceDelegate
answerOptions.reloadData()
}
}
inside cell:
class AnswersCell: UITableViewCell {
#IBOutlet weak var answerOption: UILabel!
}
and here is my view controller:
class PollsController: UIViewController, UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var questionTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
questionTableView.delegate = self
questionTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(tableView.tag)
if tableView.tag == 100 {
let cell: GeneralCell = tableView.dequeueReusableCell(withIdentifier: "GeneralCell") as! GeneralCell
cell.answerOptions.reloadData()
return cell
}else{
let cell: AnswersCell = tableView.dequeueReusableCell(withIdentifier: "AnswersCell") as! AnswersCell
return cell
}
}
func numberOfSections(in tableView: UITableView) -> Int {
if tableView.tag == 100 {
return 1
}else{
return 6
}
}
}
Then I did some test for getting to know where the problem is. I added print() into data loader function:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(tableView.tag)
if tableView.tag == 100 {
print("1")
let cell: GeneralCell = tableView.dequeueReusableCell(withIdentifier: "GeneralCell") as! GeneralCell
cell.answerOptions.reloadData()
return cell
}else{
print("2")
let cell: AnswersCell = tableView.dequeueReusableCell(withIdentifier: "AnswersCell") as! AnswersCell
return cell
}
}
and in the output I saw only one tag:
100
and as I see inside table view can't be loaded but I can't understand why. Maybe someone of you will find problem or mistake?
I suggest you use only one tableview, here some example
struct Answer {
let answerText: String
}
struct Question {
let questionText: String
let answers: [Answer]
}
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var questions: [Question] = []
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...10 {
let question = Question(questionText: "Question \(i)", answers: [
Answer(answerText: "Answer 1 Question \(i)"),
Answer(answerText: "Answer 2 Question \(i)"),
Answer(answerText: "Answer 3 Question \(i)"),
Answer(answerText: "Answer 4 Question \(i)")
])
questions.append(question)
}
tableView.dataSource = self
tableView.delegate = self
tableView.sectionHeaderHeight = UITableView.automaticDimension;
tableView.estimatedSectionHeaderHeight = 44
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return questions.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questions[section].answers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AnswerCell", for: indexPath) as! AnswerCell
cell.answerLabel.text = questions[indexPath.section].answers[indexPath.row].answerText
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionCell") as! QuestionCell
cell.questionLabel.text = questions[section].questionText
return cell
}
}
Try this
class GeneralCell : UITableViewCell {
#IBOutlet weak var answerOptions: UITableView!
#IBOutlet weak var questionText: UILabel!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(tableView.tag)
if tableView == questionTableView{
let cell: GeneralCell = tableView.dequeueReusableCell(withIdentifier: "GeneralCell") as! GeneralCell
cell.answerOptions.delegate = self
cell.answerOptions.dataSource = self
cell.answerOptions.reloadData()
return cell
}else{
let cell: AnswersCell = tableView.dequeueReusableCell(withIdentifier: "AnswersCell") as! AnswersCell
return cell
}
}

HeaderCell is only being added once to table view

To display each user input I created a table view which displays an array of structs. It works fine, but I'm currently trying to add a headerCell to each entry displaying the date of the input.
Therefore I created another cell called DateCell displaying the date. Additionally I added: func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) to the TableViewController.
My approach is working, but only partially - the DateCell is being displayed but only once with all timelineCells containing the entries underneath. Every time a entry and therefore a timelineCell is being added, the date inside of the DateCell is solely being updated, but I want every timelineCell to have its own DateCell with its own date.
TableViewController
class TimelineViewController: UIViewController {
#IBOutlet weak var toolbar: UIToolbar!
#IBOutlet weak var timlineView: UITableView!
#IBOutlet weak var buttonBack: UIBarButtonItem!
let defaults = UserDefaults.standard
var isAsc = false
override func viewDidLoad() {
super.viewDidLoad()
sortArray()
self.setToolbarInvisible(toolbar: toolbar)
timlineView.delegate = self
timlineView.dataSource = self
setShadow()
}
...
func sortArray() {
addDataArray.sort(by: { $1.date < $0.date })
}
}
extension TimelineViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return addDataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let rowData = addDataArray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineCell") as! TimelineCell
cell.setDrivenKm(drivenKm: rowData.driven)
cell.setConsumedL(consumedL: rowData.consumedL)
cell.setPricePerLiter(pricePerLiter: rowData.pricePerLiter)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let rowData = addDataArray[section]
let headerCell = tableView.dequeueReusableCell(withIdentifier: "DateCell") as! DateCell
headerCell.setDate(date: rowData.date)
return headerCell
}
}
HeaderCell
class DateCell: UITableViewCell {
#IBOutlet weak var dateLabel: UILabel!
func setDate(date: Date) {
let date = date
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let currentDate = formatter.string(from: date)
dateLabel.text = currentDate
}
}
As Sean mentioned in his comment, you can create a section for every entry of addDataArray.
You need to return sections count and change numberOfRows to 1 in each section. Also you need to change the way you retrieve data for you timeline cells, using section instead of row.
So you need to change your UITableViewDelegate methods like this:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return addDataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let rowData = addDataArray[indexPath.section]
let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineCell") as! TimelineCell
cell.setDrivenKm(drivenKm: rowData.driven)
cell.setConsumedL(consumedL: rowData.consumedL)
cell.setPricePerLiter(pricePerLiter: rowData.pricePerLiter)
return cell
}
Alternatively you can double your cells count and return both header and items as cells
Then you need to make these changes:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return addDataArray.count * 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row % 2 == 0 {
let rowData = addDataArray[indexPath.row / 2 ]
let headerCell = tableView.dequeueReusableCell(withIdentifier: "DateCell") as! DateCell
headerCell.setDate(date: rowData.date)
return headerCell
} else {
let rowData = addDataArray[indexPath.row / 2]
let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineCell") as! TimelineCell
cell.setDrivenKm(drivenKm: rowData.driven)
cell.setConsumedL(consumedL: rowData.consumedL)
cell.setPricePerLiter(pricePerLiter: rowData.pricePerLiter)
return cell
}
}
I've created a playground to show an example. Check it out here.

UITableView changing image and title position cell by cell

I was wondering if there any possible way to create a table view with this style:
I have a dictionary contains title and image values, I need to create a cell one Image-Right / Title-Left and next vice versa. How can achieve something like this?
You can do it by setAffineTransform in this way:
• build up your tableView with one prototype cell that has an image in left and a label in right
• then do this:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath) as! YourTableViewCell
if (indexPath.row % 2 == 0) {
cell.contentView.layer.setAffineTransform(CGAffineTransform(scaleX: -1, y: 1))
cell.YourImage.layer.setAffineTransform(CGAffineTransform(scaleX: -1, y: 1))
cell.YourLabel.layer.setAffineTransform(CGAffineTransform(scaleX: -1, y: 1))
}
// do what ever you want ...
return cell
}
also the best solution is defining 2 prototype cells but in your case this is a tricky and fast way to achieve your goal.
Yes, you can use a table view to achieve your requirement. you will need to follow the following steps.
Method 1:
Create two table view cell XIB's one with left side label and right side image, the second one is with left side image and right side image.
Keep same class of both the XIB's you have created but with different identifiers.
In your Table view cellForRowAtIndexPath method implement following logic.
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasourceArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row % 0 == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: "RightLabelTableViewCell", for: indexPath) as! CustomTablViewCell
cell.model = datasourceArray[indexPath.row]
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "LeftLabelTableViewCell", for: indexPath) as! CustomTablViewCell
cell.model = datasourceArray[indexPath.row]
return cell
}
}
}
Note: You can use one class for TableViewCell with a different
identifier and design your xib's accordingly.
Method 2:
Flip your table view cell's content view in a such a way that they will swap in your UI.
add the following code into your cellForRowAtIndexPath and also add else part of it because cell for a row may behave weirdly because of dequeing:
extension UIView {
/// Flip view horizontally.
func flipX() {
transform = CGAffineTransform(scaleX: -transform.a, y: transform.d)
}
}
Usage:
cell.contentView.flipX()
cell.yourImage.flipX()
cell.youImageName.flipX()
Don't forget to add else part in cellForRowAt method.
There are actually many ways of doing this:
Create 2 cells. Have 2 cells like OddTableViewCell and EvenTableViewCell. You can choose with index path which to use in cellForRow method like:
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row%0 == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: "EvenTableViewCell", for: indexPath) as! EvenTableViewCell
cell.model = dataArray[indexPath.row]
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "OddTableViewCell", for: indexPath) as! OddTableViewCell
cell.model = dataArray[indexPath.row]
return cell
}
}
}
Have a single cell but duplicate views so you have 2 labels and 2 image views. Then hide them as you need to:
class MyCell: UITableViewCell {
#IBOutlet private var leftImageView: UIImageView?
#IBOutlet private var rightImageView: UIImageView?
#IBOutlet private var leftLabel: UILabel?
#IBOutlet private var rightLabel: UILabel?
var userImage: UIImage? {
didSet {
refresh()
}
}
var userName: String? {
didSet {
refresh()
}
}
var imageOnLeft: Bool = false {
didSet {
refresh()
}
}
func refresh() {
leftImageView?.image = imageOnLeft ? userImage : nil
leftImageView?.isHidden = !imageOnLeft
rightImageView?.image = imageOnLeft ? nil : userImage
rightImageView?.isHidden = imageOnLeft
leftLabel?.text = imageOnLeft ? nil : userName
leftLabel?.isHidden = imageOnLeft
rightLabel?.text = imageOnLeft ? userName : nil
rightLabel?.isHidden = !imageOnLeft
}
}
Have a single cell with stack view. Add a label and image view onto the stack view. You can change order of items in stack view. Some promising answer can be found here. The rest should be pretty similar to the second solution.
(4.) Also you could just use a collection view and have a label cell and an image cell.
Create one cell with 2 image and 2 label left and right
when you went to left side image that time hide right side image same as in label.
cell
import UIKit
class TestTableViewCell: UITableViewCell {
#IBOutlet weak var lbl_left: UILabel!
#IBOutlet weak var lbl_right: UILabel!
#IBOutlet weak var img_right: UIImageView!
#IBOutlet weak var img_left: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configure_cell(left:Bool)
{
if left{
img_left.isHidden = true
img_right.isHidden = false
lbl_left.isHidden = false
lbl_right.isHidden = true
self.img_right.image = UIImage(named: "testimg")
}else{
img_left.isHidden = false
img_right.isHidden = true
lbl_left.isHidden = true
lbl_right.isHidden = false
self.img_left.image = UIImage(named: "testimg")
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ViewController
extension ViewController:UITableViewDataSource,UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "TestTableViewCell", for: indexPath) as? TestTableViewCell
if (indexPath.row + 1) % 2 == 0 {
cell?.configure_cell(left: true)
} else {
cell?.configure_cell(left: false)
}
return cell!
}
}

How i can fill two different tableview in one viewcontroller in swift 3

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == table1{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! acntTableViewCell
cell.account.text = account[indexPath.row].email
return cell
}
else if tableView == table2 {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2")
as! popTableViewCell
cell2.pop.text = pop[indexPath.row].answer
return cell2
}
}//its give me error here Missing return in function
I am going to fill two different tables in one viewcontroller. when I return cell it give me error Missing return in function where I am doing wrong can any one suggest me what's wrong with this code
In the first place, you should compare tables using === (references), not ==.
This is one of the cases when an assertion failure is a good way to tell the compiler that no other way of the function exists e.g.:
if tableView === table1 {
return ...
} else if tableView === table2 {
return ...
} else {
fatalError("Invalid table")
}
You can also use a switch:
switch tableView {
case table1:
return ...
case table2:
return ...
default:
fatalError("Invalid table")
}
Both answers are correct, but I believe the best way to do it would be to separate each table view to have its own data source object, not a view controller. Putting multiple tableview data source protocols adds a decent amount of unnecessary code, and if you refactor them into separate objects, you can help avoid a Massive View Controller.
class FirstTableViewDataSource : NSObject, UITableViewDataSource {
var accounts: [ObjectTypeHere]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return accounts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! AcntTableViewCell
cell.account.text = accounts[indexPath.row].email
return cell
}
}
class SecondTableViewDataSource : NSObject, UITableViewDataSource {
var pops: [ObjectTypeHere]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PopTableViewCell
cell.account.text = pops[indexPath.row].answer
return cell
}
}
From there, just update the tableviews to pull from these objects
override func viewDidLoad() {
super.viewDidLoad()
self.table1.dataSource = FirstTableViewDataSource()
self.table2.dataSource = SecondTableViewDataSource()
}
The compiler is analyzing what will happen if tableView is neither table1 nor table2. If that should happen, the function will exit with nothing to return.
That's an error.
Your cellForRowAt method should always return a cell, so
Try this way
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == table1{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! acntTableViewCell
cell.account.text = account[indexPath.row].email
return cell
}
//if tableView is not table1 then
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2")
as! popTableViewCell
cell2.pop.text = pop[indexPath.row].answer
return cell2
}
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var table1: UITableView!
#IBOutlet weak var table2: UITableView!
let firstClassRef = FirstTableView()
let secondClassRef = SecondTableView()
override func viewDidLoad() {
super.viewDidLoad()
firstClassRef.array1 = ["1","2","3"]
secondClassRef.array2 = ["1","2","3","1","2","3"]
self.table1.dataSource = firstClassRef
self.table2.dataSource = secondClassRef
self.table1.delegate = firstClassRef
self.table2.delegate = secondClassRef
self.table1.reloadData()
self.table2.reloadData()
}
}
class FirstTableView: NSObject, UITableViewDataSource, UITableViewDelegate {
var array1 = Array<Any>()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return array1.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as UITableViewCell
cell.textLabel?.text = array1[indexPath.row] as? String
cell.backgroundColor = UIColor.yellow
return cell
}
}
class SecondTableView: NSObject, UITableViewDataSource, UITableViewDelegate {
var array2 = Array<Any>()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return array2.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as UITableViewCell
cell.textLabel?.text = array2[indexPath.row] as? String
cell.backgroundColor = UIColor.yellow
return cell
}
}
Use Switch Statement
import UIKit
class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
#IBOutlet weak var topTableView: UITableView!
#IBOutlet weak var downTableview: UITableView!
var topData : [String] = []
var downData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
topTableView.delegate = self
downTableview.delegate = self
topTableView.dataSource = self
downTableview.dataSource = self
for index in 0...20 {
topData.append("Top Table Row \(index)")
}
for index in 10...45 {
downData.append("Down Table Row \(index)")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfRow = 1
switch tableView {
case topTableView:
numberOfRow = topData.count
case downTableview:
numberOfRow = downData.count
default:
print("Some things Wrong!!")
}
return numberOfRow
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
switch tableView {
case topTableView:
cell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath)
cell.textLabel?.text = topData[indexPath.row]
cell.backgroundColor = UIColor.green
case downTableview:
cell = tableView.dequeueReusableCell(withIdentifier: "downCell", for: indexPath)
cell.textLabel?.text = downData[indexPath.row]
cell.backgroundColor = UIColor.yellow
default:
print("Some things Wrong!!")
}
return cell
}
}

how to expand or replace the cell with another cell, when an particular cell select in table view

I have already asked this doubt/problem in SO. but not get get solution. Please help me out....
i have one table view which will show the list of name data till 10 datas. But what i need is , when user press any cell, that cell should be replace with another cell, which have some image, phone number, same data name. How to do that.
I have two xib : 1. normalcell, 2. expandable/replace cell
Here is my viewconrolelr.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var Resultcount: UILabel!
var tableData = ["thomas", "Alva", "Edition", "sath", "mallko", "techno park",... till 10 data]
let cellSpacingHeight: CGFloat = 5
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var nib = UINib(nibName:"customCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
Resultcount.text = "\(tableData.count) Results"
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.tableData.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return cellSpacingHeight
}
// Make the background color show through
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.clearColor()
return headerView
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:customCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! customCell
cell.vendorName.text = tableData[indexPath.section]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Starting my cell will look like this :
When i press that cell, i need some thing to do like this with replace ment of like below cell :
But when i press same cell again, again it should go to normal cell.
How to do that ??
First modify your tableView:cellForRowAtIndexPath: implementation as follows. Then you need to implement the click handler. One way would be in the MyCell class. Another would be to override selectRowAtIndexPath. Without knowing more about what you want (e.g. multiple vs single selection), it's hard to give actual code but here's something.
BOOL clickedRows[MAX_ROWS]; // Init this array as all false in your init method. It would be better to use NSMutableArray or something similar...
// selectRowAtIndexPath code
int row = indexPath.row
if(clickedRows[row]) clickedRows[row]=NO; // we reverse the selection for the row
else clickedRows[row]=YES;
[self.tableView reloadData];
// cellForRowAt... code
MyCell *cell = [tableView dequeueResuableCell...
if(cell.clicked) { // Nice Nib
[tableView registerNib:[UINib nibWithNibName... for CellReuse...
} else { // Grey Nib
[tableView registerNib:[UINib nibWithNibName... for CellReuse...
}
You need to create two independent cell on xib. Then you can load using check.You can copy and paste it will work perfectly.
in cellForRowAt like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if selectedIndexPath == indexPath && self.isExpand == true{
let cell = tableView.dequeueReusableCell(withIdentifier: "LeaveBalanceExpandedCell", for: indexPath) as! LeaveBalanceExpandedCell
cell.delegate = self
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "LeaveBalanceNormalCell", for: indexPath) as! LeaveBalanceNormalCell
return cell
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// cell.animateCell(cell)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedIndexPath == indexPath{
if isExpand == true{
self.isExpand = false
}
else{
self.isExpand = true
}
}
else{
selectedIndexPath = indexPath
self.isExpand = true
}
self.tableView.reloadData()
}

Resources