Search code examples
iosuitableviewswift3textcolor

how to change color of the part of header title in tableView in swift 3?


I have read similar questions But I didn't got the answer : I have Table View With Headers and the first one has title and a number I want to change the color of that number in the header in table view here is my codes :

var headerList = ["Account" , "Help" , "" ]

override func viewDidLoad() {
         super.viewDidLoad()
self.headerList[0] = "Account \(userAccountMoney)"

 }
  override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25))
    returnedView.backgroundColor = UIColor.init(red: 229/255, green: 233/255, blue: 236/255, alpha: 1.0)

    let label = UILabel(frame: CGRect(x: -20, y: 7, width: view.frame.size.width, height: 25))
    label.text = self.headerList[section]
    label.textAlignment = .right
    label.textColor = .lightGray
 }

as you See in my codes the header Titles Are Gray But I want in the first header Title the Account word Still be Gray But the userAccountMoney be the Green the problem is that because userAccountMoney is another variable I couldn't use similar questions


Solution

  • If you want to change the color of a part of a string you need to use NS(Mutable)AttributedString and add the color attribute only to the specific range:

    if section == 0 {
        let sectionTitle = self.headerList[0]
        let attributedString = NSMutableAttributedString(string: sectionTitle)
        if sectionTitle.characters.count > 8 {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 8, length: sectionTitle.characters.count - 8))
        }
        label.attributedText = attributedString
    } else {
        label.text = self.headerList[section]
    }
    

    The index 8 is the hard-coded index after "Account "


    However in your case I'd recommend to create headerList as constant

    let headerList = ["" , "Help" , "" ]
    

    then delete the code in viewDidLoad and use this code to create the account amount dynamically

    if section == 0 {
        let attributedString = NSMutableAttributedString(string: "Account ")
        attributedString.append(NSAttributedString(string: "\(userAccountMoney)", attributes: [NSForegroundColorAttributeName : UIColor.red]))
        label.attributedText = attributedString
    } else {
        label.text = self.headerList[section]
    }