I have a UITableView that displays a list of items. The table view controller has an array of items that gets updated asynchronously upon response from a call to a web service. Here is an example of what I have (in Swift):
class MyTableViewController : UITableViewController {
var items: [ItemClass] = []
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("RootCell", forIndexPath: indexPath) as UITableViewCell
if indexPath.section == 0 {
let item = items[indexPath.row]
cell.textLabel!.text = item.name
}
else if indexPath.section == 1 {
// Another section not shown here
}
return cell
}
}
I want each section of this table to have a footer with a button in it, so I also include this:
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let button = UIButton.buttonWithType(.System) as UIButton
button.setTitle("Add", forState:UIControlState.Normal)
if section == 0 {
button.addTarget(self, action:Selector("itemAddPressed:"), forControlEvents:UIControlEvents.TouchUpInside)
}
else if section == 1 {
// other section not shown here
}
return button
}
Items are added to the items array via an callback that gets invoked outside of the main UI thread. It looks something like this:
private func itemWasAdded(item: ItemClass) {
dispatch_async(dispatch_get_main_queue()) {
self.items += [item]
self.tableView!.reloadData()
}
}
This all works fine, but my use of the table's reloadData seems like overkill to me when I know that only one item is being added at a time. So, I tried to update it to do the following:
private func itemWasAdded(item: ItemClass) {
dispatch_async(dispatch_get_main_queue()) {
self.items += [item]
let indexPath = NSIndexPath(forRow:self.item.count - 1, inSection:0)
self.tableView!.insertRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
}
When I do it this way, the table continues to work but there's a problem with the footer buttons. Instead of showing the Add button I've created in each section's footer, I see the add button for section 0 showing at the bottom of the table view, underneath section 1.
It seems like doing something to force a refresh of the table seems to fix the problem. This UITableViewController is the top controller in a UINavigationController, and if I select a table cell a new view controller is pushed onto the navigation controller. Navigating back to the original table view controller, the footer buttons are displayed in the correct place.
The easiest way to make this work is just to use reloadData instead of insertRowsAtIndexPaths. But I'd like to know what I'm doing wrong here so that I can avoid reloading all table data if possible.
Am I using the insertRowsAtIndexPaths incorrectly here?
I thought this is happening because beginUpdates() and endUpdates() were missing and it would be very simple mistake. But I had exactly a same problem when I tested it.
I will just share my observations.
When I try with tableview style Grouped, the problem above is not happening. But if I use Plain style, the footer goes down to the bottom of the tableview. I guess there's something to do with different footer view behaviors depending on its style and the way table view layout its content after updating its data.
If you have to use tableview with Plain style, you have to handle the case where the sum of its contents' heights( cells and section footer views) is less than the tableview height right before inserting a row.
Something like,
let contentHeight = CGFloat(items.count * cellHeight + numberOfSection*footerHeight)
if contentHeight < tableViewHeight {
tableView.frame = CGRectMake(0, 0, view.frame.size.width, numberOfSection*CGFloat(items.count * cellHeight + footerHeight))
} else {
tableView.frame = viewHeight
}
In order to make everything clean, you should understand what are the behaviors of section footer/header of tableview with its different style and frames. Hope that you can find the better solution that meets your requirements.
Related
I am changing the numberOfLines attribute on a label that lives in a custom UITableViewCell when the cell is tapped. However, this is not reflected in the UI until the second tap. The cell is configured as a prototype cell in the table view to initially have 2 lines.
Interestingly enough, when I print out the numberOfLines value before and after my tapped() function runs, the values start off different, and then synchronize - after the first tap, I see 2 lines before the function runs, then 0 lines after the function runs. However, after subsequent taps, I see the same value before and after my function, which makes it seem like it's not doing anything, even though the UI does stretch and shrink the cell, and the numberOfLines value is changed for the next time the didSelectRowAtIndexPath function runs.
I'm only seeing this behavior with tableView.reloadRows(). If I do a full update with tableView.reloadData(), the cell appropriately grows and collapses the first time it is tapped. However, this feels a bit ham-fisted and doesn't animate nicely like reloadRows() does.
TableView Implementation
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? ReviewTableViewCell
else { return }
let data = tableData[indexPath.row]
print("old number of lines: \(cell.detailLabel.numberOfLines)")
//data.isOpen is set to false initially
cell.tapped(data.isOpen)
tableData[indexPath.row].isOpen = !data.isOpen
tableView.reloadRows(at: [indexPath], with: .fade)
print("old number of lines: \(cell.detailLabel.numberOfLines)")
// tableView.reloadData()
}
Custom Table View Cell method
func tapped(_ isOpen: Bool) {
if !isOpen {
detailLabel.numberOfLines = 0 }
else {
detailLabel.numberOfLines = 2 }
}
I am expecting this code to expand the cell once it is reloaded with tableView.reloadRows() if the numberOfLines is set to 0 and collapse the cell when it is set to 2. This does work, but only after tapping the cell two+ times. This should work with the first tap as well.
Here is a link of a gif that shows the issue: https://imgur.com/a/qe2uAXj
Here is a sample project that is similar to what's going on in my app: https://github.com/imattice/CellLabelExample
Just to be clear, to get this trick work UILabel generally must be constrained on each side to it's superview, in this way when it changes its intrinsicContentSize is able to push each side to accomodate the text.
Saying that, try to wrap the tapped method with those two methods:
tableView.beginUpdates()
if !isOpen {
detailLabel.numberOfLines = 0
}
else {
detailLabel.numberOfLines = 2
}
tableView.endUpdates()
Of course tableview must be set to automatic size:
tableView.estimatedRowHeight = <#What you want#>
tableView.rowHeight = UITableView.automaticDimension
I was able to work out what was going on. The problem is in two parts.
The first part is calling reloadRows(). This method is swapping out the cells with a new cell rather than updating the cell that already exists. Therefore, I'm changing the number of lines on that hidden swap cell rather than the cell that is in view. This behavior is mentioned in the docs:
Reloading a row causes the table view to ask its data source for a new cell for that row. The table animates that new cell in as it animates the old row out.
Additionally, I'm using structs as the data model for tracking the open status of the cell. In Swift, structs are copy-on-write, which means that if a value is changed on that struct, a new struct is created rather than changing the value of that struct I'm pointing to. This means the line tableData[indexPath.row].isOpen = !data.isOpen doesn't do anything useful - we look at the tableData struct at the index path, get it's isOpen value, copy a new struct and change that new struct's isOpen value, and then throw it out because the new struct is not assigned anywhere.
The solution is to not use the reloadRows() method and to either use
A) a class for the data object
B) replace the data at indexPath.row to the copied struct
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? CustomCell else { return }
var data = tableData[indexPath.row]
tableView.beginUpdates()
cell.tapped(isOpen: data.isOpen)
data.isOpen = !data.isOpen
tableData[indexPath.row] = data
tableView.endUpdates()
}
I'm using RxDataSources to load and display a UITableview. I am trying to update the section header with the amount of items that it holds, however tough the cell and items update correctly, the title remains stale.
This is my code for the DataSource object:
tableViewDataSource = RxTableViewSectionedAnimatedDataSource<TableViewParticipationSection>(
configureCell: { (_, tableView, _, item) in
return TableViewCellType.transformData(item).cell(inTableView: tableView)
}, titleForHeaderInSection: { dataSource, index in
let sectionModel = dataSource.sectionModels[index]
return "\(sectionModel.items.count)"
})
The identity of the section header is just {return 0} since I only have a single section.
Furthermore I have confirmed that if I use this code:
DispatchQueue.main.asyncAfter(deadline: .now()+3, execute: {
self?.contentView.tableView.reloadData()
})
It will actually update the section title, so it seems to be some problem with staleness but I can't seem to track it down.
Does anyone have experience with dynamic titles using RxDataSources
Edit:
After further experiments, the title will update, if I scroll around in the tableview, the title changes at some point.
Turns out that the title or any data on the section model is not included in the diff, so no matter what you do, it won't make a difference. The RxDataSource doesn't support non static headers. The solution is to make a custom view and do the binding myself.
In my case I set new empty UIView for section in
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let customHeaderViewMulti = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView") as! CustomHeaderView
return customHeaderView
}
// This is WRONG:
return UIView()
}
You must return nil for other cases.
I have a table view with custom cells. They are quite tall, so only one cell is completely visible on the screen and maybe, depending on the position of that cell, the top 25% of the second one. These cells represent dummy items, which have names. Inside of each cell there is a button. When tapped for the first time, it shows a small UIView inside the cell and adds the item to an array, and being tapped for the second time, hides it and removes the item. The part of adding and removing items works fine, however, there is a problem related to showing and hiding views because of the fact that cells are reused in a UITableView
When I add the view, for example, on the first cell, on the third or fourth cell (after the cell is reused) I can still see that view.
To prevent this I've tried to loop the array of items and check their names against each cell's name label's text. I know that this method is not very efficient (what if there are thousands of them?), but I've tried it anyway.
Here is the simple code for it (checkedItems is the array of items, for which the view should be visible):
if let cell = cell as? ItemTableViewCell {
if cell.itemNameLabel.text != nil {
for item in checkedItems {
if cell.itemNameLabel.text == item.name {
cell.checkedView.isHidden = false
} else {
cell.checkedView.isHidden = true
}
}
}
This code works fine at a first glance, but after digging a bit deeper some issues show up. When I tap on the first cell to show the view, and then I tap on the second one to show the view on it, too, it works fine. However, when I tap, for example, on the first one and the third one, the view on the first cell disappears, but the item is still in the array. I suspect, that the reason is still the fact of cells being reused because, again, cells are quite big in their height so the first cell is not visible when the third one is. I've tried to use the code above inside tableView(_:,cellForRow:) and tableView(_:,willDisplay:,forRowAt:) methods but the result is the same.
So, here is the problem: I need to find an EFFICIENT way to check cells and show the view ONLY inside of those which items are in the checkedItems array.
EDITED
Here is how the cell looks with and without the view (the purple circle is the button, and the view is the orange one)
And here is the code for the button:
protocol ItemTableViewCellDelegate: class {
func cellCheckButtonDidTapped(cell: ExampleTableViewCell)
}
Inside the cell:
#IBAction func checkButtonTapped(_ sender: UIButton) {
delegate?.cellCheckButtonDidTapped(cell: self)
}
Inside the view controller (NOTE: the code here just shows and hides the view. The purpose of the code is to show how the button interacts with the table view):
extension ItemCellsTableViewController: ItemTableViewCellDelegate {
func cellCheckButtonDidTapped(cell: ItemTableViewCell) {
UIView.transition(with: cell.checkedView, duration: 0.1, options: .transitionCrossDissolve, animations: {
cell.checkedView.isHidden = !cell.checkedView.isHidden
}, completion: nil)
}
EDITED 2
Here is the full code of tableView(_ cellForRowAt:) method (I've deleted the looping part from the question to make it clear what was the method initially doing). The item property on the cell just sets the name of the item (itemNameLabel's text).
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier:
ItemTableViewCell.identifier, for: indexPath) as? ItemTableViewCell{
cell.item = items[indexPath.row]
cell.delegate = self
cell.selectionStyle = .none
return cell
}
return UITableViewCell()
}
I've tried the solution, suggested here, but this doesn't work for me.
If you have faced with such a problem and know how to solve it, I would appreciate your help and suggestions very much.
Try this.
Define Globally : var arrIndexPaths = NSMutableArray()
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tblVW.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
cell.textLabel?.text = String.init(format: "Row %d", indexPath.row)
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: #selector(btnTapped), for: .touchUpInside)
if arrIndexPaths.contains(indexPath) {
cell.backgroundColor = UIColor.red.withAlphaComponent(0.2)
}
else {
cell.backgroundColor = UIColor.white
}
return cell;
}
#IBAction func btnTapped(_ sender: UIButton) {
let selectedIndexPath = NSIndexPath.init(row: sender.tag, section: 0)
// IF YOU WANT TO SHOW SINGLE SELECTED VIEW AT A TIME THAN TRY THIS
arrIndexPaths.removeAllObjects()
arrIndexPaths.add(selectedIndexPath)
self.tblVW.reloadData()
}
I would keep the state of your individual cells as part of the modeldata that lies behind every cell.
I assume that you have an array of model objects that you use when populating you tableview in tableView(_:,cellForRow:). That model is populated from some backend service that gives you some JSON, which you then map to model objects once the view is loaded the first time.
If you add a property to your model objects indicating whether the cell has been pressed or not, you can use that when you populate your cell.
You should probably create a "wrapper object" containing your original JSON data and then a variable containing the state, lets call it isHidden. You can either use a Bool value or you can use an enum if you're up for it. Here is an example using just a Bool
struct MyWrappedModel {
var yourJSONDataHere: YourModelType
var isHidden = true
init(yourJSONModel: YourModelType) {
self.yourJSONDataHere = yourJSONModel
}
}
In any case, when your cell is tapped (in didSelectRow) you would:
find the right MyWrappedModel object in your array of wrapped modeldata objects based on the indexpath
toggle the isHidden value on that
reload your affected row in the table view with reloadRows(at:with:)
In tableView(_:,cellForRow:) you can now check if isHidden and do some rendering based on that:
...//fetch the modelObject for the current IndexPath
cell.checkedView.isHidden = modelObject.isHidden
Futhermore, know that the method prepareForReuse exists on a UITableViewCell. This method is called when ever a cell is just about to be recycled. That means that you can use that as a last resort to "initialize" your table view cells before they are rendered. So in your case you could hide the checkedView as a default.
If you do this, you no longer have to use an array to keep track of which cells have been tapped. The modeldata it self knows what state it holds and is completely independent of cell positions and recycling.
Hope this helps.
So I'm having a problem with updating the height of a UITableViewCell when the text of its label gets changed.
I'm not good at explaining thing, therefore I've created a repo on Github so that you can just grab and run. The problem should show up when you scroll up and down the table view (to make the cell reused).
What I did was:
I created a table view with self-size cells.
Each of the cells has a UILabel in it.
I have a view model that will decide what's in the UILabel.
I use RxSwift to register the changes in the view model and update the text of the UITable accordingly.
At the same time, the cell will ask its delegate (in this case, the UITableViewController) to recalculate its height.
The delegate will then call tableView.beginUpdates and tableView.endUpdates to update the height of the cell.
Results:
When I scroll up the table view so that the first cell gets reused and then scroll down. The content of the first cell is duplicated across the table view (the second cell becomes a duplicate of the first one.)
What I tried:
I tried to call tableView.reloadData(). -> Infinite Loop
I tried to call tableView.reloadRows() -> This works but I don't know why.
What I want to achieve:
I want to keep Rx and MVVM together since I like the way Rx works.
I want to be able to change the label text of the cell and the height of the cell can be updated to fit the text.
Some code snippets: (Although it'd better to go check the repo out.):
Cell register view model
override func awakeFromNib() {
super.awakeFromNib()
viewModel.title
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] title in
guard let cell = self else { return }
cell.label.text = title
cell.delegate?.requestSizeRecalculate(cell: cell)
})
.disposed(by: disposeBag)
}
Delegate methods in UITableViewController
func requestSizeRecalculate(cell: SimpleCell) {
print("Size recalculating....")
method1(cell: cell)
//method2(cell: cell)
//method3(cell: cell)
}
private func method1(cell: SimpleCell) {
// Will not cause infinite loop but will have duplicates.
cell.setNeedsUpdateConstraints()
tableView.beginUpdates()
tableView.endUpdates()
}
private func method2(cell: SimpleCell) {
// Will cause infinite loop
tableView.reloadData()
}
private func method3(cell: SimpleCell) {
// This method works pretty well.
if let indexPath = tableView.indexPath(for: cell) {
tableView.reloadRows(at: [indexPath], with: .none)
}
}
It's my first time asking questions on Stackoverflow. I know I might have made things more complicated than it should be. But if anyone can offer any suggestions based on your experience, I would appreciate very much!
You can do:
tableView.beginUpdates()
tableView.reloadRows(at: [indexPathOfCell], with: .none)
tableView.endUpdates()
I have seen your code. Now you don't need to Calculate Height of row. when you give just top , leading , bottom and Trailing constrain. Xcode will calculate height of label and increase cell size According to label height. you need to pass just 1 method.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
you have done all the things correctly. you need to just write above method. Don't required this method now.
extension ViewController: SimpleCellDelegate {
func requestSizeRecalculate(cell: SimpleCell) {
print("Size recalculating....")
I have uploaded your project on this link with changes. Added 1 more large text in array to test self sizing.
Self Sizing Tableview
Here is Screenshot of Out:-
I hope this answer is helpful for you.
I would like to hide some elements in a custom cell when we overpass a specific number of row. I added more row than the ones visible, because I needed to scroll until the last row without the bouncing effect. But now I have more cells, and I don't need the cells after row > 13.
I tried to setNeedsDisplay the cell with a if else, but the dequeue... method has a bad effect on the cells, when I scroll up, back to the previous cells, they don't have the texts anymore, like the row > 13. Is there a way to use the dequeue method, and let the content for the rows < 13, and remove the content for the rows > 13 ?
Here is some code :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var identifier = ""
if tableView == self.tableView{
identifier = "MyCell"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as MyCell
if indexPath.row < 14 {
cell.showContent = true
cell.label.text = "test\(indexPath.row)"
}
else {
cell.showContent = false
cell.label.text = ""
cell.addItem.text = ""
}
cell.setNeedsDisplay()
return cell
}
//MyCell
override func drawRect(rect: CGRect) {
if !showContent {
label.text = ""
addItem.text = ""
}
else {
let path = UIBezierPath()//custom separator that should not be drawn for row > 13
Thanks
You shouldn't modify the text this way in drawRect. You already modified the labels in cellForRow. That's all you need.
That said, this isn't how I would do it. I'd probably create a different cell with its own identifier for empty cells. That way they can be really simple and you don't have to do things like cell.setNeedsDisplay() to get rid of the separator line. So in cellForRow, just return one kind of cell for data rows, and a different kind of cell for empty rows. There's no rule that says all the cells have to be the same class.