我有一個UITableView
我加載了一些應用程序設置。我需要表格是單選的,並且由於表格保存了設置,因此可能有一些單元格會根據設置啓用狀態以編程方式選擇。indexPathForSelectedRow返回零,但我有一個單元格編程選擇
目前,我遇到一個奇怪的行爲,其中,如果以編程方式選擇一個單元格,然後indexPathForSelectedRow
回報nil
(當它應該返回我選擇的單元格的指數),因此當我在第二電池接頭(改變當前選定的設置)我最終選擇了兩個單元格(即使在我的tableView對象中將allowMultipleSelection
設置爲false)。
這裏是我的代碼:
override func viewDidLoad() {
tableView.allowsMultipleSelection = false
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("myCell")
if let cell = cell {
// tableObject is an array containing settings model
let row = tableObject[indexPath.row]
cell.textLabel!.text = row.settingValue
if row.selected {
cell.setSelected(true, animated: false)
cell.accessoryType = .Checkmark
}
cell.tag = row.id
}
return cell!
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
// oldIndex is always nil for the cell I called setSelected in cellForRowAtIndexPath
if let oldIndex = tableView.indexPathForSelectedRow {
if let oldCell = tableView.cellForRowAtIndexPath(oldIndex) {
tableView.deselectRowAtIndexPath(oldIndex, animated: true)
oldCell.accessoryType = .None
}
}
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.setSelected(true, animated: true)
cell.accessoryType = .Checkmark
}
return indexPath
}
override func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .None
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
return indexPath
}
任何想法,我怎麼能總是在同一時間只選擇了一個單元格?
謝謝!
你需要使用DIDSELECT不將選擇和方法,你已經有了indexpath你爲什麼不喜歡tableView.indexPathForSelectedRow –
@NitinGohel代碼帶上面的代碼甚至當我改變它使用didSelectRow我仍然觀察到相同的行爲 – mradzinski
讓我發表一個答案給我幾個薄荷 –