ios - 为什么我选择单元格时字体没有改变?

标签 ios swift uitableview

当我选择单元格时,我打印数组中的位置,它在控制台中正确打印,但是当我尝试将字体更改为粗体以指示单元格已被选中时,没有任何变化。

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/

相关文章:

iphone - 可调整大小的 UITableViewCell

swift:类或结构是否可以具有一种无需点符号即可访问的 "main"属性?

ios - 寄存器有什么问题(_ :forCellWithReuseIdentifier:) on UICollectionView?

SWIFT 对具有特定对象的不同对象集合的单元格进行排序

objective-c - xcode重新加载tableview

ios - Segue 不工作(不再)?

ios - 自 IOS 8 使用自动布局和 ScrollView 以来额外的顶部空白

ios - 解析.com includeKey : not working

ios - Xcode 6.4 - 无法对 View 或任何内容设置约束

swift - 如何创建一个结构体来将 JSON 反序列化为具有多级节点的结构