我创建了以下代码,以便在选择和取消选择单元格时更改文本颜色。然而问题是,当加载 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/