在cellForRowAt indexPath方法之外获取选定的行号

时间:2019-12-29 14:15:25

标签: ios swift uitableview

我需要访问cellForRowAt indexPath方法之外的所选行。我目前正在做的是使用Int来跟踪已选择的行,并在cellForRowAt indexPath内分配该值,以便以后可以将Int用作当前选择的行

一切正常,但我想确保没有其他方法可以不必使用Int变量。

是否有一种方法可以在cellForRowAt indexPath方法之外获取选定的行号,而不必使用Int变量来跟踪行号?

var selectedRow:Int?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    selectedRow = indexPath.row
}

func myFunction(){
    let indexPath = IndexPath(row:selectedRow!, section: 1)
    let cell = self.myTable.cellForRow(at: indexPath) as! CustomCell
}

2 个答案:

答案 0 :(得分:1)

您可以尝试使用indexPathForSelectedRow

guard let index =  self.myTable.indexPathForSelectedRow ,  
      let cell = self.myTable.cellForRow(at: index) as? CustomCell 
else { return }

答案 1 :(得分:1)

您还可以从didSelectRowAt委托方法中调用函数:

["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun","Mon","Tue"]