I'm trying to add a UITableViewCell to another UITableView section whenever a button on the cell is tapped. However, I'm quite confused about the process of how to change a cell's section location after it has already been loaded into the table view. Currently I have two sections and am adding 5 custom UITableViewCells into the first section.
Any ideas on how to move the cells to the second section on tap?
Here are cell and section methods in my view controller class:
var tableData = ["One","Two","Three","Four","Five"]
// Content within each cell and reusablity on scroll
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var tableCell : Task = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Task
tableCell.selectionStyle = .None
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
var titleString = "Section \(indexPath.section) Row \(indexPath.row)"
tableCell.title.text = titleString
println(indexPath.row)
return tableCell
}
// Number of sections in table
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
// Section titles
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "First Section"
} else {
return "Second Section"
}
}
// Number of rows in each section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return tableData.count
} else if section == 1 {
return 0
} else {
return 0
}
}
You need to have a separate datasource for first and second sections. When button is tapped, modify datasource and move cell to new section with moveRowAtIndexPath(indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) UITableView method.
For example:
var firstDataSource = ["One","Two","Three","Four","Five"]
var secondDataSource = [ ]
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return section == 0 ? firstDataSource.count : secondDataSource.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = indexPath.section == 0 ? firstDataSource[indexPath.row] : secondDataSource[indexPath.row]
return cell
}
// For example, changing section of cell when click on it.
// In your case, similar code should be in the button's tap event handler
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if indexPath.section == 0
{
let data = firstDataSource[indexPath.row]
tableView.beginUpdates()
secondDataSource.append(data)
firstDataSource.removeAtIndex(indexPath.row)
let newIndexPath = NSIndexPath(forRow: find(secondDataSource, data)!, inSection: 1)
tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath)
tableView.endUpdates()
}
}
Related
I am having trouble making a table view with one static cell at the very top of my table view. This table view will hold 4 buttons and the rest of the views will hold a list of the user's songs.
I have already looked into other answers on here but all of them seem to be written in Objective C not swift.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedSongs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCell", for: indexPath) as! RecentCell
//cell.songTitle.text = albumList[indexPath.row]
//cell.songArtist.text = artistList[indexPath.row]
//cell.songImage.image = imageList[indexPath.row]
return cell
}
This is what I have been using to just set the regular table views. How would I go about modifying this code to allow for a static cell at the top and dynamic cells for the rest?
Don't use Static Cells. Choose Dynamic Prototypes in your table view and create 2 prototype cells.
And return first cell in first section, other cells in second section
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
return sortedSongs.count
} else if section == 2 {
return anotherArrayCount
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) as! FirstCell
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCell", for: indexPath) as! RecentCell
//cell.songTitle.text = albumList[indexPath.row]
//cell.songArtist.text = artistList[indexPath.row]
//cell.songImage.image = imageList[indexPath.row]
return cell
}
}
You can use the HeaderView of the table for that, just give your custom view to the . tableHeaderView property
Example:
override func viewDidLoad() {
super.viewDidLoad()
let myCustomView = MyCustomView()
tableView.tableHeaderView = myCustomView
}
Documentation: https://developer.apple.com/documentation/uikit/uitableview/1614904-tableheaderview
I am currently using two prototype cells to have my collectionView in top cell moving horizontally while all other cells moves vertical. It's still short one cell count at the bottom and I can't seem to figure out why.
This is the code. Can you point out where the issue is please?
//Mark:- Data arrays
var dataArray: [String] = ["c1","c2","c3","c4","c5"]
var cellArray: [String] = ["10","11","12","13","14","15"]
//Mark:- UITableView Delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell") as! MainTableViewCell
return cell
} else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
cell2.cellImage.image = UIImage(named: cellArray[indexPath.row])
return cell2
}
}
//Mark:- UICollectionView Delegate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InsideCollectionViewCell", for: indexPath) as! InsideCollectionViewCell
cell.myImage.image = UIImage(named: dataArray[indexPath.row])
return cell
}
It seems you want your table view to contain the values in your cellArray array plus one extra special row at index 0.
In order to do this you need to indicate that there is an extra row and your indexing needs to account for the extra row.
But a simpler approach is to use multiple sections in your table view. Use section 0 for the extra special row and use section 1 for the values in your cellArray.
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? 1 : cellArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell") as! MainTableViewCell
return cell
} else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
cell2.cellImage.image = UIImage(named: cellArray[indexPath.row])
return cell2
}
}
Make sure you adjust for the use of multiple sections in any other table view method you may implement (such as didSelectRowAt, etc.).
For the sake of comparison, here is how you would need to change your code if you want all of the rows in one section:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellArray.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell") as! MainTableViewCell
return cell
} else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
cell2.cellImage.image = UIImage(named: cellArray[indexPath.row - 1])
return cell2
}
}
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
}
}
By default each section should show maximum three cells. If any cell contains more than three cells, it should display 'show more' option.If show more is tapped I want to display the rest of the cells in that particular section. Two days I spent, nothing worked out.Segments at the top of the table. Depend on segment selected, tableview load the cells. This code for each segment each section varies, so the func cellForRowAtIndexPath: becomes big seriously very big. I roughly added code. This code is what i have tried.
if segmentName == .Feature || segmentName == .Services
{
if indexPath.section == 0
{
if boolShowFullFeature[indexPath.section] == false
{
if indexPath.row == showCells
{
return createShowMoreCell(indexPath.section)
}
else
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SearchListViewCell
var firstTitle = "", secondTitle = "", thirdTitle = "", recomendValue = "", starValue = ""
(firstTitle, secondTitle, thirdTitle, recomendValue, starValue) = model.foodValue[indexPath.row]
cell.configureCell(firstTitle, secondTitle: secondTitle, thirdTitle: thirdTitle, recomendValue: recomendValue, starValue: starValue)
return cell
i had actually done this before. here is sample code:
var objects = [["1","2","3"],["q","w","e","r","t","y"],["z","x","c","v","b","n","m"]]
var sec = ["sec a","sec b","sec c"]
var showallSec = 0
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sec.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let items = objects[section].count
if items > 3{
if section == showallSec-1{
return items
}
return 4
}
return items
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.section][indexPath.row]
cell.textLabel!.text = object
if(indexPath.section != showallSec-1){
if(indexPath.row == 3){
cell.textLabel!.text = "show more"
}}
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sec[section]
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if(indexPath.row == 3){
showallSec = indexPath.section + 1
tableView.reloadData()
}
}
I Want to add a UIButton to my UITableViewCell.My cells expands in height when it is selected.. The button must only be displayed when didSelectRow is called in the expanded area ... I have 4 cells that I want to populate with different questions, forms and buttons. Should I sub-class each cell?
This is my code so far:
let SelectedCellHeight: CGFloat = 500.0
let UnselectedCellHeight: CGFloat = 44.0
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let logItemCell = tableView.dequeueReusableCellWithIdentifier("LogCell", forIndexPath: indexPath) as! UITableViewCell
}
// Used to expand cell when selected
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
if let selectedCellIndexPath = selectedCellIndexPath {
if selectedCellIndexPath == indexPath {
return SelectedCellHeight
}
}
return UnselectedCellHeight
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
if let selectedCellIndexPath = selectedCellIndexPath {
if selectedCellIndexPath == indexPath {
self.selectedCellIndexPath = nil
} else {
self.selectedCellIndexPath = indexPath
}
} else {
selectedCellIndexPath = indexPath
}
tableView.beginUpdates()
tableView.endUpdates()
}
Yes, you should make 4 prototype cells with different identifier and class and return the one you want in 'cellForRowAtIndexPath' depending on the indexPath.
You should subclass each cell that you want. And when didSelectRow is called and the cell is expanded button.hidden = false should be called