Search code examples
uitableviewswiftuicolor

Swift viewForHeaderInSection not working with custom colors


I'm experiencing very strange behaviour of the tableView's viewForHeaderInSection method:

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 30.0
}

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

    let label = UILabel(frame: CGRectMake(10.0, 10.0, tableView.frame.size.width, 30.0)) // Doesn't care about x, y offset
    label.text = "Results"
    label.textColor = UIColor.blueColor()
    label.backgroundColor = UIColor.orangeColor() // Not Working: UIColor(red: 88, green: 130, blue: 202, alpha: 1.0)

    return label
}
  1. Regardless which values I choose in the CGRectMake constructor my label will always stick to the upper left corner.
  2. The textColor and backgroundColor attributes are working with standard UIColor colors e.g. UIColor.blueColor(), but failing with colors like UIColor(red: 88, green: 130, blue: 202, alpha: 1.0) -> Not showing anything at all

Can you guys help me fix this issue?


Solution

  • Use this:

        let newRed = CGFloat(88)/255
        let newGreen = CGFloat(130)/255
        let newBlue = CGFloat(202)/255
    
        self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)