【发布时间】:2018-05-15 12:54:22
【问题描述】:
我在表格视图中选择正确的单元格时遇到问题。我的代码是:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var MyTableView: UITableView
var cellsArray = [ "0" , "1" , "2" , "3" , "4" , "5" , "6" , "7"]
override func viewDidLoad() {
super.viewDidLoad()
MyTableView.layer.borderWidth = 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 8
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = MyTableView.dequeueReusableCell(withIdentifier: "cells", for: indexPath)
cell.textLabel?.text = cellsArray[indexPath.row]
return cell
}
@IBAction func MyButtonClick(_ sender: Any) {
let myIndexPath = IndexPath(row: 4 ,section: 0)
let cell = MyTableView.cellForRow(at: myIndexPath)
cell?.backgroundColor = UIColor.yellow
}
This is the application when it's running
问题是当我按下按钮而不滚动表格视图时没有任何反应,但如果我向下滚动以使当前视图包含标记为 4/5/6 的单元格并按下按钮标记为“4”和“0”的两个单元格都有他们的背景颜色设置为黄色。
我最终想知道为什么会出现这种情况,因为它影响的不仅仅是背景,例如在执行 for 循环以对单元格高度求和以自动更改 tableview 的高度时,不在视图中的单元格会崩溃程序,因为它返回 null。
任何帮助将不胜感激!
在看到 4 时按下按钮后
【问题讨论】:
标签: ios swift uitableview