ios - 设置选定的单元格而不推送到新的 viewController

标签 ios swift uitableview

我创建了以下代码,以便在选择和取消选择单元格时更改文本颜色。然而问题是,当加载 View 时,所有标题标签都是灰色的,我希望选择第一个单元格。但是我似乎无法找到如何做?我尝试将第一个单元格设置为另一种颜色,但是当我选择另一个单元格时,它不会更改为灰色。我怎样才能做到这一点?

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

     var cell = tableView.cellForRowAtIndexPath(indexPath) as! MenuViewCell

        cell.titleLabel?.textColor = UIColor(rgba: "#E91E63")

}


override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

        var cell = tableView.cellForRowAtIndexPath(indexPath) as! MenuViewCell
        cell.titleLabel?.textColor = UIColor.whiteColor()

}

最佳答案

您可以创建另一个函数并在 didSelectRowAtIndexPath 方法中写入您想要进行的更改。例如。

func applySelectionChangesToCell(cell:UITableViewCell) {
     cell.textLabel?.textColor = UIColor.redColor()
}

现在您可以从 didSelectRowAtIndexPath 方法和 viewDidAppear/表重新加载后调用此函数。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     var cell = tableView.cellForRowAtIndexPath(indexPath)
     applySelectionChangesToCell(cell!)
}

override func viewDidAppear(animated: Bool) {
     super.viewDidAppear(animated)
     let indexPath = NSIndexPath(forRow: 0, inSection: 0)
     let cell = self.tableView.cellForRowAtIndexPath(indexPath)

     if let cell = cell {
          self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
          applySelectionChangesToCell(cell)
     }
}

关于ios - 设置选定的单元格而不推送到新的 viewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31945616/

相关文章:

ios - “NSInternalInconsistencyException” - 无法在 uinavigationcontroller ios 6 上推送 uitableviewcontroller

ios 8 在滚动时隐藏导航 Controller 并在向上滚动一点时再次显示

ios - 我的 iOS 应用程序上的评价应用程序按钮

iphone - 使用 Cocoa 在 uitableview 中编辑单元格

ios - Swift 中奇怪的保留周期

ios - 如何在当前 Collection View 中显示 xib

swift - 数据未显示在 TableView Swift CoreData 中

c# - TableView 单元格在滚动时重置其数据

php - 从 iOS 模拟器向本地主机发送 Post 请求

swift - '[任务] ?' is not convertible to ' 可选<[任何]>'