Swift: How do I achieve adding a background color to a tableView textLabel

770 Views Asked by At

I'm working with TableView and I was hoping to add a background colour to a selected cell's text. Something like this:

The image represents a cell, the background color is separated. This is what is needed.

enter image description here I tried doing the following but it adds a background colour to the entire cell or to the text only.

The separation between is the most important, adding a backgroundColor applys a color to the entire cell, which is not wanted.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {  //Highlighting text - Add saving text
    let cell = tableView.cellForRow(at: indexPath)
    print("You selected cell number: \(indexPath.row)!")
    cell?.textLabel?.textColor = .yellow
    cell?.textLabel?.backgroundColor = .yellow // Is not desired outcome
}
4

There are 4 best solutions below

3
Zyfe3r On

Your image shows a textlabel with yellow background colour and black text colour.

If you are trying to change the background colour, it should be

cell?.textLabel?.backgroundColor = UIColor.yellow

cell?.textLabel?.textColor = UIColor.yellow is used to change the text colour and not the background colour.

( https://www.youtube.com/watch?v=DCc5MKKpfUA . This will help you)

let searchString = "Lorem Lorem"
 let baseString = "Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum"



let attributed = NSMutableAttributedString(string: baseString)
    do
    {
        let regex = try! NSRegularExpression(pattern: searchString,options: .caseInsensitive)
        for match in regex.matches(in: baseString, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: baseString.characters.count)) as [NSTextCheckingResult] {
            attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow, range: match.range)
        }
        self.txtView.attributedText = attributed
    }
1
Angel F Syrus On

First you have to add a global variable for identify which cell is selected.

var selectedIndex = -1

And update the value according to selected row

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {  //Highlighting text - Add saving text
    self.selectedIndex = indexPath.row
    tabeview.reoadData()
}

and write the cellForRow as,

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell= (tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! YourCell)

        if self.selectedIndex == indexPath.row
        {
           cell?.textLabel?.backgroundColor = UIColor.yellow
        }
        else
        {
            cell?.textLabel?.backgroundColor = UIColor.yellow
        }

       return cell!
    }
0
Glenn Posadas On

TheTiger user is correct. All you need to learn is setting your label's attributedText. I've worked on tons of Bible applications with same highlighting verse feature.

From what I can remember, the attribute name is: NSBackgroundColorAttributeName. Good luck!

1
Yogesh Tandel On

Modify the below code to use as per your requirement

 cell?.textLabel?.attributedText = self.decorateText(myTxtOne: "Use this", myTxtTwo: " Code")


func decorateText(myTxtOne:String, myTxtTwo:String)->NSAttributedString{
    let textAttributeOne = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.backgroundColor: UIColor.blue, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]
let textAttributeTwo = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.backgroundColor: UIColor.yellow, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]

    let textPartOne = NSMutableAttributedString(string: myTxtOne, attributes: textAttributeOne)
    let textPartTwo = NSMutableAttributedString(string: myTxtTwo, attributes: textAttributeTwo)

    let textCombination = NSMutableAttributedString()
    textCombination.append(textPartOne)
    textCombination.append(textPartTwo)
    return textCombination
}