[英]How can I change text color of certain cells in UITableView?
So, I'm making an app in Xcode 6 (Swift 1). 因此,我正在使用Xcode 6(Swift 1)开发一个应用程序。 I'm trying to make certain cells' text colors green, and others' red, however, I'm not successful.
我试图将某些单元格的文本颜色设置为绿色,将其他单元格的颜色设置为红色,但是,我没有成功。 Here's my code:
这是我的代码:
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)!")
}
}
And here's my code for changing the universal text color: 这是我用于更改通用文本颜色的代码:
cell.textLabel.textColor = [UIColor greenColor];
So, for example, how can I make the "green" cell green, and the "red" cell red? 因此,例如,如何使“绿色”单元格变为绿色,而使“红色”单元格变为红色? Thanks!
谢谢!
After the var items
declaration, add this: 在
var items
声明之后,添加以下内容:
let itemColors = [UIColor.greenColor(), UIColor.redColor()]
In tableView(_:cellForRowAtIndexPath:)
, add this before the return statement: 在
tableView(_:cellForRowAtIndexPath:)
,将其添加在return语句之前:
cell.textLabel?.textColor = itemColors[indexPath.row]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.