tableview data repeat when scrolling - ios

I use a custom cell to show the placeholder but scrolling the table repeats the placeholder
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! AddTableViewCell
cell.textInfo.delegate = self
if textPlaceHolders![indexPath.row].containsString("Category") == true {
cell.selected = true
cell.textInfo.text = textPlaceHolders![indexPath.row]
cell.accessoryType = .DisclosureIndicator
} else {
cell.textInfo.placeholder = textPlaceHolders![indexPath.row]
}
return cell
}
I tried some solution like this the problem resolved but when user end edit the text disappear
class AddTableViewCell: UITableViewCell {
#IBOutlet weak var textInfo: UITextField!
override func prepareForReuse() {
textInfo.text= ""
}
}

In your case you assign text property for cell's textInfo outlet in one case and placeholder in another. Because of UITableView's reuse policy your textInfo contains placeholder/text even if you haven't specified it for concrete indexPath. So you need to clean it up for every indexPath if you don't want them. Like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! AddTableViewCell
cell.textInfo.delegate = self
if textPlaceHolders![indexPath.row].containsString("Category") == true {
cell.selected = true
cell.textInfo.text = textPlaceHolders![indexPath.row]
cell.textInfo.placeholder = nil
cell.accessoryType = .DisclosureIndicator
} else {
cell.textInfo.placeholder = textPlaceHolders![indexPath.row]
cell.textInfo.text = nil
}
return cell
}

Related

Single and MultiSelection cells in same tableView | Swift

Before duplicating this question, please be known that I've spent days on this issue, working hours, and looking for all same sort of questions on SO, but there is something I am missing or doing wrong.
I have a tableView in which the data is being populated via API response. Below is the model I have.
struct Model : Codable {
let bugClassification : [Bug]?
}
struct Bug : Codable {
let selectable : String? //Telling wether cell is single/Multi selected
var options : [Options]?
}
struct Options : Codable, Equatable {
let title : String?
let id: Int
var isCellSelected: Bool = false
}
Scenario
I want to create multiple sections, each having different cell depending upon the type of selectable, either single or multi. I have achieved that, but the problem I am getting is that whenever I scroll, random cells are also selected. Now, I know this behaviour is because of tableView reusing the cells. But I am confused as how to handle all this. Also, I want to put the validation on the sections, that is, every section should have atleast one cell selected. Kindly guide me in the right direction, and any small help would be appreciated. Below is my code.
CellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if bugClassification[indexPath.section].selectable?.lowercased() == "multi-select" {
//Multi-Selection
let cell = tableView.dequeueReusableCell(withIdentifier: multiSelectionCellID) as! MultiSelectionCell
let item = bugClassification[indexPath.section].options![indexPath.row]
cell.label.text = item.title
if item.isCellSelected {
cell.checkMarkImageView.alpha = 1
cell.checkMarkView.layer.borderColor = UIColor.white.cgColor
cell.checkMarkView.backgroundColor = .emerald
} else if item.isCellSelected {
cell.checkMarkImageView.alpha = 0
cell.checkMarkView.layer.borderColor = UIColor.veryLightBlue.cgColor
cell.checkMarkView.backgroundColor = .white
}
return cell
} else {
//Single-Selection
let cell = tableView.dequeueReusableCell(withIdentifier: singleSelectionCellID) as! SingleSelectionCell
let item = bugClassification[indexPath.section].options![indexPath.row]
cell.label.text = item.title
if item.isCellSelected {
cell.checkMarkImageView.alpha = 1
cell.checkMarkView.layer.borderColor = UIColor.emerald.cgColor
} else {
cell.checkMarkImageView.alpha = 0
cell.checkMarkView.layer.borderColor = UIColor.veryLightBlue.cgColor
}
return cell
}
}
DidSelectRow Method
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if bugClassification[indexPath.section].selectable?.lowercased() == "multi-select" {
var item = bugClassification[indexPath.section].options![indexPath.row]
item.isCellSelected = !item.isCellSelected
bugClassification[indexPath.section].options![indexPath.row] = item
self.tableView.reloadRows(at: [indexPath], with: .automatic)
} else {
let items = bugClassification[indexPath.section].options
if let selectedItemIndex = items!.indices.first(where: { items![$0].isCellSelected }) {
bugClassification[indexPath.section].options![selectedItemIndex].isCellSelected = false
if selectedItemIndex != indexPath.row {
bugClassification[indexPath.section].options![indexPath.row].isCellSelected = true
}
} else {
bugClassification[indexPath.section].options![indexPath.row].isCellSelected = true
}
self.tableView.reloadSections([indexPath.section], with: .automatic)
}
}
In cellForRowAt
if item.isCellSelected == true{
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
and update the model by every selection
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let item = bugClassification[indexPath.section].options![indexPath.row]
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
if indexPath.section == 0{
item.isCellSelected.isSelected = false
}else{
item.isCellSelected.isSelected = false
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = bugClassification[indexPath.section].options![indexPath.row]
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
if indexPath.section == 0{
item.isCellSelected.isSelected = true
}else{
item.isCellSelected.isSelected = true
}
}
}

UITableView Checkmarks at the wrong place after search

I want to search in my tableView, set checkmarks and save the objects with the checkmarks in Realm. But if I set a checkmark after a search and cancel the search, the checkmark is at the indexPath that I clicked on, and not at the object. I can't explain it better, so here's an example:
After I search an exercise.
After I clicked the cancel button
Here's my code:
class ShowExcercisesTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
//Properties
let realm = try! Realm()
var request2: Results<Excercise>?{
didSet{
tableView.reloadData()
}
}
var searchOrNot: Excercise?
var searchResults = try! Realm().objects(Excercise.self)
var resultSearchController: UISearchController!
var shouldShowSearchResults = false
var muscleGroupForSearch: String?
//Searchbar Funktionen
func filterResultsWithSearchString(searchString: String){
let predicate = NSPredicate(format: "name CONTAINS [c]%# AND muscleGroup =%# AND copied = false", searchString, muscleGroupForSearch!)
searchResults = realm.objects(Excercise.self).filter(predicate).sorted(byProperty: "name", ascending: true)
}
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text
filterResultsWithSearchString(searchString: searchString!)
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
shouldShowSearchResults = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
shouldShowSearchResults = false
tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if !shouldShowSearchResults {
shouldShowSearchResults = true
tableView.reloadData()
}
resultSearchController.searchBar.resignFirstResponder()
}
//Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.searchBar.delegate = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
controller.searchBar.placeholder = "Suche Übungen..."
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
self.tableView.reloadData()
}
//TableView Funktionen
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if shouldShowSearchResults {
return searchResults.count
}
else{
return request2!.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ShowExcercisesTableViewCell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.showExcercises, for: indexPath) as! ShowExcercisesTableViewCell
if shouldShowSearchResults{
let excercise = searchResults[indexPath.row]
cell.nameLabel.text = excercise.name
if fromTrainingPlan{
if excercise.selected == true{
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
}
return cell
}
else{
let excercise = request2![indexPath.row]
cell.nameLabel.text = excercise.name
if fromTrainingPlan{
if excercise.selected == true{
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
}
return cell
}
}
//Checkmarks
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if fromTrainingPlan == true && request2 != nil{
if shouldShowSearchResults{
searchOrNot = searchResults[indexPath.row]
}
else{
searchOrNot = request2![indexPath.row]
}
tableView.deselectRow(at: indexPath, animated: true)
let cell: ShowExcercisesTableViewCell = tableView.cellForRow(at: indexPath) as! ShowExcercisesTableViewCell
do {
try realm.write {
searchOrNot!.selected = !searchOrNot!.selected
}
}
catch{
print(error)
}
if searchOrNot!.selected {
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
}
}
Sorry for so much code, I'm not sure what is relevant and what not. Is there any way to set the checkmarks at the right places after the search? Thanks in advance!
It's working now.
In your cellForRowAtIndexPath, you need to disable the checkmark for cells that do not need it. You are only enabling for cells that do.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ShowExcercisesTableViewCell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.showExcercises, for: indexPath) as! ShowExcercisesTableViewCell
if shouldShowSearchResults{
let excercise = searchResults[indexPath.row]
cell.nameLabel.text = excercise.name
if excercise.selected == true{
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none // Add this code here
}
return cell
}
else{
let excercise = request2![indexPath.row]
cell.nameLabel.text = excercise.name
if excercise.selected == true {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none // Add this code here
}
return cell
}
}
UITableViews reuse the cells internally. So when you are searching, you are saying cell one has a checkmark, then when you cancel, it goes back to the table and looks at the cells and your cellForRow code never tells it that cell one is no longer checked, thus it maintains the checkmark there. The cell is not being recreated, its already exists, so you cannot make an assumption about what state it is in (not checked or checked).
the checkmark is at the indexPath that I clicked on
You are not telling the code on what indexPath you want the checkmark. When your cell gets reused :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
You need to keep a reference to what indexPath is supposed to be selected and show the checkMark so the cells shows the checkMark on the correct indexPath when the cells are reused internally.
EDIT:
Seems some people downvote and modify my answers as their own without reading how the framework works and reading Apples Documentation.
Reusable Cells
prepareForReuse
If a UITableViewCell object is reusable—that is, it has a reuse
identifier—this method is invoked just before the object is returned
from the UITableView method dequeueReusableCellWithIdentifier:. For
performance reasons, you should only reset attributes of the cell that
are not related to content, for example, alpha, editing, and selection
state. The table view's delegate in tableView:cellForRowAtIndexPath:
should always reset all content when reusing a cell. If the cell
object does not have an associated reuse identifier, this method is
not called. If you override this method, you must be sure to invoke
the superclass implementation.

Pass variable to custom UITableViewCell from UIViewController

Here is how I use my custom UITableViewCell RunningTableViewCell inside UIViewController:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! RunningTableViewCell
//.......
cell.isTop = false
if(indexPath.row == 0){
cell.isTop = true
}
cell.isBottom = false
if(indexPath.row == myArray.count-1){
cell.isBottom = true
}
return cell
}
And here is my RunningTableViewCell class: (Cell's GUI is made inside storyboard)
class RunningTableViewCell: UITableViewCell {
//#IBOutlet ...
#IBOutlet weak var myButton: SomeButton!
var isTop: Bool?
var isBottom: Bool?
override func awakeFromNib() {
super.awakeFromNib()
print("result: \(self.isTop) \(self.isBottom)")
myButton.isTop = self.isTop
myButton.isBottom = self.isBottom
}
}
It returns result: nil nil
The usage of the result is: (SomeButton is a subview inside RunningTableViewCell)
class SomeButton: UIButton {
var isTop = false
var isBottom = false
override func drawRect(rect: CGRect) {
if(isTop){
// DO SOMETHING...
}
if(isBottom){
// DO SOMETHING...
}
}
}
So how can I pass data to RunningTableViewCell?
awakeFromNib is called right after the view and its subviews were allocated and initialized.
So your code from awakeFromNib in RunningTableViewCell for each cell is called before delegate method func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell. That is why isTop and isBottom are nil in awakeFromNib.
You can define method in RunningTableViewCell, which will load cell with this variables.
func load(isTop: Bool, isBottom: Bool) {
self.isTop = isTop
self.isBottom = isBottom
// Update cell UI as you wish
}
And finally rewrite delegate method func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell in your view controller.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! RunningTableViewCell
let isTop = indexPath.row == 0
let isBottom = indexPath.row == myArray.count-1
cell.load(isTop, isBottom: isBottom)
return cell
}
You need to override prepareForReuse in the cell. And remove it from tableView:indexPath:. So when you scroll the cell is going to be reused but the isBotton and isTop vars will be reseted.
override func prepareForReuse() {
self.isBottom = false
self.isTop = false
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! RunningTableViewCell
//.......
cell.isTop = false
if(indexPath.row == 0){
cell.isTop = true
cell.tag=100
}
cell.isBottom = false
if(indexPath.row == myArray.count-1){
cell.isBottom = true
cell.tag=200
}
return cell
}
and also get this like ...
class RunningTableViewCell: UITableViewCell {
//#IBOutlet ...
var isTop: Bool?
var isBottom: Bool?
override func awakeFromNib() {
super.awakeFromNib()
if (self.tag==100)
{
isTop=true
}
else if (self.tag==200) {
isBottom=true
}
else{
isTop=false
isBottom=false
}
print("result: \(self.isTop) \(self.isBottom)")
}
}
And also do using singleton methods...
You can resolve this issue by call custom method in your cell like,
inside UIViewController:
//.......
cell.isTop = false
if(indexPath.row == 0){
cell.isTop = true
}
cell.isBottom = false
if(indexPath.row == myArray.count-1){
cell.isBottom = true
}
cell.UpdateViews()
return cell
}
inside TableViewCell:
//#IBOutlet ...
var isTop: Bool?
var isBottom: Bool?
func updateViews() {
print("result: \(self.isTop) \(self.isBottom)")
}
Good luck!

UITableViewCell not hiding UIView properly

I want to hide/unhide an UIView in the UITableViewCell, but many times it unhides it for the wrong UITableViewCell. Any suggestions?
cellForRowAtIndexPath function
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("locationCell", forIndexPath: indexPath) as? UITableViewCell
var viewWithImage = cell?.viewWithTag(22) as UIView!
var cellHiddenGemView = viewWithImage?.viewWithTag(23) as UIView!
var locationObject : PFObject = locationObjects[indexPath.row] as! PFObject
var isSecret = locationObject["isSecret"] as! Bool
cellHiddenGemView?.hidden = true;
if isSecret == true
{
cellHiddenGemView?.hidden = false;
//this view is unhides for the wrong indexes also
}
return cell;
}
Its definitely not the best solution to use tags instead of subclassing UITableViewCell and use IBOutlets.
If you would subclass UITableViewCell you could override prepareForReuse()
and reset the hidden property to true
func prepareForReuse()
{
self.HiddenGemView?.hidden = true
}
Try defining else block too. Once this worked for me.
if isSecret == true
{
cellHiddenGemView?.hidden = false;
}
else
{
cellHiddenGemView?.hidden = true;
}

swift update cell accessory type

I am trying to update my table cell accessory type when I tap a cell.
here is the code:
var selectedCellArray :[FriendTableViewCell] = []
var friends: [PFUser] = []
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var selectedCell = self.tableView(tableView, cellForRowAtIndexPath: indexPath) as FriendTableViewCell
if (selectedCell.accessoryType == UITableViewCellAccessoryType.None){
selectedCell.accessoryType = .Checkmark
selectedCellArray.append(selectedCell)
}else if (selectedCell.accessoryType == UITableViewCellAccessoryType.Checkmark){
selectedCell.accessoryType = .None
var index = 0
for cell in selectedCellArray{
if (cell != selectedCell){
index++
}else{
break
}
}
selectedCellArray.removeAtIndex(index)
}
self.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
and
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("friend") as? FriendTableViewCell ?? FriendTableViewCell()
var round = 0
var friend: AnyObject = self.friends[indexPath.row]
cell.firstNameLabel.text = friend["firstName"] as? String
cell.lastNameLabel.text = friend["lastName"] as? String
println(selectedCellArray)
round++
var hasFound = false
if (self.checkSelectedArray(selectedCellArray, target: cell)){
cell.accessoryType = .Checkmark
}else{
cell.accessoryType = .None
}
cell.firstNameLabel.sizeToFit()
cell.lastNameLabel.sizeToFit()
return cell
}
func checkSelectedArray(selectedArray:[FriendTableViewCell], target:FriendTableViewCell) -> Bool{
for cell in selectedCellArray{
if cell.isEqual(target){
return true
}
}
return false
}
Also, is there a built-in method like array.contain? Currently, I wrote a function by myself to check if an array has certain element......
Please help me out... I am stuck for this problem for about 8 hours
Storing the reference to the cell isn't a valid strategy as cells can be re-used when the table scrolls. You can't use the current cell accessory to indicate selection state for the same reason.
You can use an NSIndexSet or a Swift dictionary. Here is an implementation using a dictionary -
var selectedCells :Dictionary<String,PFUser>()
var friends: [PFUser] = []
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as FriendTableViewCell
let objectId=friends[indexPath.row].objectId
if (selectedCells[objectId] != nil){
selectedCell.accessoryType = .None
selectedCells.removeValueForKey(objectId)
} else
selectedCell.accessoryType = .Checkmark
selectedCells[objectId]=friends[indexPath.row]
}
tableView.deselectRowAtIndexPath(indexPath, animated:false)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("friend") as? FriendTableViewCell ?? FriendTableViewCell()
var round = 0
var friend: AnyObject = self.friends[indexPath.row]
cell.firstNameLabel.text = friend["firstName"] as? String
cell.lastNameLabel.text = friend["lastName"] as? String
if (selectedCells[friend.objectId] != nil){
selectedCell.accessoryType = .Checkmark
} else
selectedCell.accessoryType = .None
}
cell.firstNameLabel.sizeToFit()
cell.lastNameLabel.sizeToFit()
return cell
}

Resources