Disable selection of a cell without UserInteractionEnabled in Swift - ios

I have a cell with a button and setting UserInteractionEnabled to false disables the button too. Now if I use cell.selectionStyle = UITableViewCellSelectionStyle.None. Although the cell doesn't get highlighted but I loose the previous selected cell. Any way to overcome this?

Implement the UITableView delegate method
tableView(_ tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
Return nil for the row you don't want to be able to be selected.

... and for Swift 3, the delegate method is:
public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.row == 0 {
return nil
} else {
return indexPath
}
}

Related

Selection of UITableViewCell Changes when Scroll down in Swift

I am using a UITableView and what I am doing is I am changing the color of the cell when I tap on the cell using didSelectRow function of UITableView at cellForRowAt. The thing which is bothering me is when I scroll down or scroll up, those cells whom I changed the color before were changed to other cells. Here is my code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell
cell.backView.backgroundColor = .white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = myTableView.cellForRow(at: indexPath) as! TasksTableViewCell
cell.backView.backgroundColor = UIColor(named: "primaryViewColor")
}
Does anyone knows why this happens? Does anyone has a solution that when only those cells changes color whom I tap on, and when I scroll down or move up only those cells have the other color?
cellForRowAt will be called every time that cell is displayed.
you need selected list to save selected index.
var listSelected: [Int] = []
and
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell
cell.backView.backgroundColor = listSelected.contains(indexPath.row) ? UIColor(named: "primaryViewColor") : .white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if listSelected.contains(indexPath.row) {
listSelected = listSelected.filter{$0 != indexPath.row}
} else {
listSelected.append(indexPath.row)
}
tableView.reloadRows(at: [indexPath], with: .automatic)
}
I encountered do you see the problem many times. Even if using and iVar can solve the problem, You are mixing "Controller" logic and "Model" logic.
I usually prefer to move "selection" state inside the model.
Suppose You have a class "Contact" you use to fill cell data (usual MVC pattern)
I add:
class contact{
..
var selected = false
}
AND in TV delegation method I use to apply selection, OR better I use a custom selection method in a custom cell (for example to see a √ element in cell)
As a bonus multiple selection come for free, and you can also save current selections for next run :)
So as I understand you select a cell and after that other cells look like they are selected?
If so I think this is happening because you change the background color of the cell and tableViews and collectionViews are reusing the cells, basically keeping the background you changed behind.
TableViewCells are reused as soon as they leave the visible area.
This means that a cell whose background you have colored will be deleted from the view hierarchy as soon as it is scrolled up or down. If the corresponding row is scrolled in again, the function cellForRowAt is called again for this IndexPath and the cell gets a white background.
The easiest is to save the IndexPaths of the selected cells and check in the cellForRowAt function if the current cell has to be selected.
Add the following var to the viewController class:
var selectedIndexPaths = Set<IndexPath>()
and modify the tableView delegate methods:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = myTableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell
cell.backView.backgroundColor = (selectedIndexPaths.contains(indexPath) ? UIColor(named: "primaryViewColor") : .white)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if selectedIndexPaths.contains(indexPath)
{
selectedIndexPaths.remove(indexPath)
}
else
{
selectedIndexPaths.insert(indexPath)
}
tableView.reloadRows(at: [indexPath], with: .none)
}
You can use
step 1: create model
class DemoModel {
var isSelected: Bool = false
var color: UIColor = .While
}
step 2: and in tableview
var listDemo: [DemoModel] = [DemoModel(),...]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier:
"TasksTableViewCell") as! TasksTableViewCell
var obj = listDemo[indexPath.row]
cell.backView.backgroundColor = obj.color
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var obj = listDemo[indexPath.row]
obj.color = UIColor(named: "primaryViewColor")
tableView.reloadRows(at: [indexPath], with: .automatic)
}

Remove Table View Cell from Table View with if statement

How do I remove a static table view cell by doing a if statement like this:
if ____ {
remove static cell
} else {
keep cell in tableview
}
The bolded part is what I need the code for. I searched the internet for an answer, but I could not find one. Thanks for the help! I'm using Swift 3
First, make sure to change cells to have Dynamic Properties, because static cells are hard-coded.
Second, you don't need an else statement. If the condition is true, delete the cell, otherwise do nothing. To delete a cell, use a function:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Cell deleted")
// delete any additional data from containers like arrays or dictionaries if needed
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
If this is a static tableview you can't remove a cell. If you attempt to you'll probably fall into all sorts of issues. Your best solution is to set the cell's height to zero and hide it.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt:indexPath)
if indexPath == cellToHide {
cell.isHidden = true
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == cellToHide {
return 0
}
return super.tableView(tableView, heightForRowAt: indexPath)
}

How to set custom UITableViewRowAction depending on IndexPath.row?

I have a
tableView(UITableView)
customCell: UITableViewCell!
itemsArray: [Item]
I tried to set custom action for cell in UITableView depending on IndexPath.row.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath)
-> [UITableViewRowAction]? {
if !(itemsArray[indexPath.row].isReadOnly) {
let editAction = UITableViewRowAction(style: .normal, title: "Edit") {
(tableViewRowAction, indexPath) in
print("Edit Item \(self.itemsArray[indexPath.row].caption)\n")
} 
return [editAction]
} else {
return []
}
}
I tried to set custom action for cell in UITableView depending on IndexPath.row:
The problem occurs with cells, which I want to be without actions (which corresponding items has .isReadOnly = true)
I tried to return nil and [] in else case and both variants has irrelevant result for swiping:
- nil – Delete action shows for items
- [] – Cell swipes a little bit, “unswipes” back an than swipes stops working in any cell
I found a solution: just use canEditRowAt method of UITableView
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return !(items[indexPath.row].isReadOnly)
}

Disable highlight on tableview

How to disable highlight on tableview without disable the func? i tried these and now i can't go to the another page.
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
Set the selectionStyle property of your UITableViewCell to .None.
This will permit selection but prevent the default highlighting behavior.
In the cellForRowAtIndexPath implementation in your controller, set the selectionStyle to .None as below:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.selectionStyle = .None
// ...
return cell
}
Step 1: Select your Tableview Cell
Step 2: After then go to Tableview Cell Properties and Set your
Tableview Cell Selection ".None"
Or you can also Do Programmatically add "Tablecell.selectionStyle = .none
" this code in your cellForRowAtIndexPath method.
I believe disabling selection should do the trick.
tableView.allowsSelection = false
Or, if you want the user to be able to temporarily tap the table you could do this:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//your code
tableView.deselectRowAtIndexPath(indexPath)
}

Create Action For Static Cell Clicked in UITableView

How can I make a static table view to create an action when one of the cells is clicked in Swift?
I have created a static table like a general menu of the app, I can directly create a push segue when one of the cells are clicked. But at the same time when I click to one of the seques, I want the below function to be run. By draging a cell to the UITableView in storyboard the create action option is not appearing.
var goToProfiles = PFObject(className: "goToProfile")
goToProfiles["user"] = PFUser.currentUser()!.username
goToProfiles["goToUser"] = usernameLbl.text
goToProfiles.save()
If you use sections you will also need to query them.
override func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(indexPath.section)
print(indexPath.row)
if indexPath.section == 1 && indexPath.row == 1 {
// do something
}
}
I found the solution with the code below:
override func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 1 {
//here you can enter the action you want to start when cell 1 is clicked
}
}
For swift 3 compatibility:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Your action here
}

Resources