当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - How can I change text color of certain cells in UITableView?

问题描述:

So, I'm making an app in 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:

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

In tableView(_:cellForRowAtIndexPath:), add this before the return statement:

cell.textLabel?.textColor = itemColors[indexPath.row]
分享给朋友:
您可能感兴趣的文章:
随机阅读: