Home > Blockchain >  Switch Statement on didSelectRowAt Function in Swift
Switch Statement on didSelectRowAt Function in Swift

Time:12-30

I am using a table view and has a label in its cell. The thing I want is to change the cell label on every tap of a cell. Here is my code:

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 
  let cell = tableView.cellForRow(at: indexPath)

 switch indexPath {
            
        case 1:
            
            cell.cellLabel.text = "first time label changes"
        case 2:
            
            cell.cellLabel.text = "second time label changes"
            
        default:
            cell.cellLabel.text = "change the label"
        }

} 

Now if I use:

switch indexPath.row {...}

only case 1 works. And if I use only:

switch indexPath {...}

It gives me the following error:

Expression pattern of type 'Int' cannot match values of type 'IndexPath'

Does anyone have a solution that if I tap a cell first time case 1 should work and if I tap it again case 2 should work?

CodePudding user response:

You need to save the current tap with an instance variable as indexPath.row will remain zero

let arr = ["first time label changes","second time label changes","change the label"] 
var currentIndex = 0 // you can make it 1 initially in case index 0 is pre-assigned 
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    guard currentIndex < 3 else { return } // prevent overflow taps
    let cell = tableView.cellForRow(at: indexPath) 
    cell.cellLabel.text = arr[currentIndex]
    currentIndex  = 1
} 

Another good practice also is to only refresh cell at didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    guard currentIndex < 2 else { return } // prevent overflow  
    currentIndex  = 1
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->  UITableViewCell {  
    let cell = //  
    cell.cellLabel.text = arr[currentIndex]
    return cell
} 

CodePudding user response:

try my code

var count = 0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
count  = 1
let cell = tableView.cellForRow(at: indexPath)
switch count {   
    case 1:
        cell.cellLabel.text = "first time label changes"
    case 2:
        cell.cellLabel.text = "second time label changes"
        
    default:
        cell.cellLabel.text = "change the label"
    }
} 
  • Related