【问题标题】:How can I change text color of certain cells in UITableView?如何更改 UITableView 中某些单元格的文本颜色?
【发布时间】:2016-04-19 11:57:25
【问题描述】:

所以,我正在 Xcode 6 (Swift 1) 中制作应用程序。我正在尝试使某些单元格的文本颜色为绿色,而其他单元格的文本颜色为红色,但是,我没有成功。这是我的代码:

import Foundation
import UIKit

class ViewController: UIViewController, UITableViewDelegate,     UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var items: [String] = ["green", "red"]

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.items.count;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    cell.textLabel?.text = self.items[indexPath.row]

    return cell
}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")
}
}

这是我更改通用文本颜色的代码:

cell.textLabel.textColor = [UIColor greenColor];

那么,例如,如何将“绿色”单元格设为绿色,将“红色”单元格设为红色?谢谢!

【问题讨论】:

  • 你在哪里改变单元格 textLabel 颜色?
  • 在“var items”声明之后

标签: ios xcode swift uitableview


【解决方案1】:

var items 声明之后,添加:

let itemColors = [UIColor.greenColor(), UIColor.redColor()]

tableView(_:cellForRowAtIndexPath:) 中,在return 语句之前添加:

cell.textLabel?.textColor = itemColors[indexPath.row]

【讨论】:

  • 谢谢!不过有两件事。首先,使用第二行代码“UILabel?”时出现错误。没有名为“textColor”的成员。其次,我假设我会将我想要绿色的项目放在括号之间,对吧?
  • 我已经更新了我的答案。您将项目的颜色放入 itemColors 数组中。
  • 将项目放入“let itemColors= [UIColor.greenColor(), UIColor.redColor()]”括号中时仍然出现错误。我觉得我做错了什么
  • “我仍然收到错误”信息不足。编辑您的问题以包含更新的代码和错误。复制和粘贴。不要重新输入它们。
  • 让 itemColors... 必须在视图控制器本身上声明。并且 rob 在他的示例中没有使用“绿色”,而是 UIColor.greenColor()。更新您的问题以显示您在哪里得到这些错误
猜你喜欢
  • 2017-11-04
  • 2019-08-03
  • 1970-01-01
  • 2015-06-27
  • 2016-11-15
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多