当我选择单元格时,我打印数组中的位置,它在控制台中正确打印,但是当我尝试将字体更改为粗体以指示单元格已被选中时,没有任何变化。
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell: cellsort = table.dequeueReusableCellWithIdentifier("cell") as! cellsort
cell.type.font = UIFont(name: "System-Bold", size: 17)
cell.typeselected.hidden = false
print("selected")
print(sort[indexPath.row])
}
最佳答案
因为您正在更改 UITableViewCell
的不同实例上的字体,而不是所选实例上的字体。
您应该只在数据源方法 -tableView: cellForRowAtIndexPath:
中使用 dequeue...
。该方法用于按需配置新单元格(基于您的数据模型),并将其传递给 TableView 进行显示。
而是使用 UITableView 的方法:cellForRowAtIndexPath:
(不要与数据源方法混淆!)。它为您提供屏幕上的实际单元格,如果相应的行不在屏幕上,则为 nil。来源:Apple's documentation .
编辑:我通过添加一些错误检查使代码更安全。
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell: CellSort = table.cellForRowAtIndexPath(indexPath) as! CellSort
// ^ Capitalize your class names!!!
if let cell = table.cellForRowAtIndexPath(indexPath) as? CellSort {
// Success
cell.type.font = UIFont(name: "System-Bold", size: 17)
cell.typeselected.hidden = false
print("selected")
print(sort[indexPath.row])
}
else{
// Error; Either:
// A) Cell was not found at the specified index
// path (method returned nil), or
//
// B) The returned cell (UITableViewCell) could
// not be cast to your custom subclass (CellSort).
//
// Neither should happen, if you register your cell classes
// correctly and call the above method on the same index path
// that was selected.
}
}
关于ios - 为什么我选择单元格时字体没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36324970/