0

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
}
Angel F Syrus
  • 1,984
  • 8
  • 23
  • 43
N. Der
  • 507
  • 4
  • 18
  • 1
    Its not like that what you think. To be more clear try setting the background color to `cell` and `textLabel` and then see the difference. – TheTiger Jul 29 '19 at 04:42
  • 3
    Actually you need `attributedText` and not the `textColor` only. So google for `attributedText` for label and it will solve your issue. Your question title is misleading. – TheTiger Jul 29 '19 at 04:44
  • 2
    `cell?.textLabel?.backgroundColor = .yellow` does not set the entire cell. It sets only the label. Of course it could be that the label is covering most of the cell. – rmaddy Jul 29 '19 at 05:11

4 Answers4

3

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
    }
Zyfe3r
  • 653
  • 6
  • 24
  • Hi, this adds a yellow background color to the entire cell, which is not what I want. I need the background color be specific to the text. just like in the picture! – N. Der Jul 29 '19 at 04:43
  • @N.Der Oh, now i get it. You forgot to mention that your Label fills your entire cell. I am assuming that your label has the same size as the entire cell? By using this, your cell still has white background , but the problem is that your label fills the entire cell and changing label background color makes it look like the cell color changed. For this, you need to use AttributedText – Zyfe3r Jul 29 '19 at 07:08
  • can you explain searchString and its use – N. Der Jul 31 '19 at 03:44
1

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
}
Yogesh Tandel
  • 1,738
  • 1
  • 19
  • 25
0

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!
    }
Angel F Syrus
  • 1,984
  • 8
  • 23
  • 43
  • Hi, this adds a yellow background color to the entire cell, which is not what I want. I need the background color be specific to the text. just like in the picture! The separation between is key. – N. Der Jul 29 '19 at 04:48
0

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!

Glenn Posadas
  • 12,555
  • 6
  • 54
  • 95