简体   繁体   中英

How to change the color of text in a tableview swift?

I've created a tableview in swift and I'm customising appearance to make it look nicer. I'd like to change the appearance to have a clear background and white text color. Tableview function:

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:UITableViewCell = self.myTableView
        .dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
    let score = scores[indexPath.row]
    cell.textLabel!.text = String(score.gameScore!)
    UITableViewCell.appearance().textLabel?.textColor = UIColor.whiteColor();
    UITableViewCell.appearance().backgroundColor = UIColor.clearColor();

    return cell;
}

So the second part works with the clear cells but but the first part doesn't for some reason. I checked out some sources online but can't seem to get this one right:

How to change text color in tableView section in swift

https://www.natashatherobot.com/ios-change-uitableviewcell-selection-color-app-wide/

Any help would be greatly appreciated! Thanks

You need to change the color of text using the "cell" object you created. So it should be like this

cell.textLabel?.textColor = UIColor.cyanColor()

Change it to any color of your desire

First, I don't think it's wise to use appearance() to globally alter all your cells, but if you do it, you should be, as your link says, calling it in your AppDelegate , not each time you load a cell.

Second, you can customize many of these features directly in storyboard (and since you're using a reusable cell, you really should) - go find your cell and change the text color there.

Or, as mentioned by @Umair, you can simply change that call to not be global, and change the color directly.

Just change in your table view code, like this:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Categoria")
    cell?.textLabel?.text = categoris[indexPath.row]
    cell?.textLabel?.textColor = UIColor.white // <- Changed color here
    return cell!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM