use*_*845 1 xcode uitableview ios swift
我有一个可用的 UITableview,它当前允许选择多个单元格。我只想选择一个,如果选择了前一个,则新选择应取消选中前一个。脑筋急转弯!这是我的代码:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow();
let CurrentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
if CurrentCell.imageView!.image == nil {
let SelectedCell = CurrentCell.textLabel!.text
CurrentCell.imageView!.image = UIImage(named:"check")!
CurrentCell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
println("Selected Cell is")
println(SelectedCell)
} else {
CurrentCell.imageView!.image = nil
let SelectedCell = "NothingSelected"
CurrentCell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)
println("Nothing Selected")
}
}
Run Code Online (Sandbox Code Playgroud)
管理选择状态的一个非常有效的方法是向selected数据模型添加一个属性,在这个例子中只是调用Model
class Model {
var selected = false
...
}
Run Code Online (Sandbox Code Playgroud)
在UITableViewController该类中,我们假设有一个 Arraydata将Model项目保存为表视图的数据源。
var data = [Model]()
Run Code Online (Sandbox Code Playgroud)
在cellForRowAtIndexPath设置图像和文本取决于selected属性:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyIdentifier") as! UITableViewCell
let currentItem = data[indexPath.row]
if currentItem.selected {
cell.imageView!.image = UIImage(named:"check")!
cell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
} else {
cell.imageView!.image = nil
cell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)
}
return cell
}
Run Code Online (Sandbox Code Playgroud)
在didSelectRowAtIndexPath将selected当前选定单元格的属性设置为false,将selected刚刚选定单元格的属性设置为true并重新加载表格时,更改将应用于cellForRowAtIndexPath
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
data.filter {$0.selected == true}.map {$0.selected = false}
let currentItem = data[indexPath.row]
currentItem.selected = true
tableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5468 次 |
| 最近记录: |