Search code examples
iosuitableviewswiftuiblureffectuivibrancyeffect

How to implement UIVibrancyEffect for table view header?


I would like my table view section headers text to be rendered in the vibrant style, where the underlying UI shines through the text. I have tried the following, but nothing appears for the header as if I returned nil.

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    //Add vibrancy text effect
    let blurEffect = UIBlurEffect(style: .Light)
    let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)
    let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)

    //Label for vibrant text
    let vibrantLabel = UILabel()
    vibrantLabel.text = "testing"
    vibrantLabel.font = UIFont.systemFontOfSize(11.0)
    vibrantLabel.textColor = UIColor(white: 0.64, alpha: 1)
    vibrancyEffectView.contentView.addSubview(vibrantLabel)

    return vibrancyEffectView
}

Solution

  • Solved it. The only problems with my code provided in the question are: I had to set the frames for the view and label (duh), and I needed to specify the blur effect style to be .Dark not .Light to ensure the text was light colored not dark. For anyone who has the same question, here's the code. You'll want to tweak the position/size/etc of the text I'm sure. Note that I already had applied a blur effect for the table view's background.

    //Create vibrancy text effect
    let blurEffect = UIBlurEffect(style: .dark)
    let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
    let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
    vibrancyEffectView.frame = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 40)
    vibrancyEffectView.autoresizingMask = .flexibleWidth
    
    //Create header label
    let vibrantLabel = UILabel()
    vibrantLabel.frame = vibrancyEffectView.frame
    vibrantLabel.autoresizingMask = .flexibleWidth
    vibrantLabel.text = "testing"
    vibrantLabel.font = UIFont.systemFont(ofSize: 16)
    vibrantLabel.textColor = UIColor(white: 0.64, alpha: 1)
    
    vibrancyEffectView.contentView.addSubview(vibrantLabel)
    return vibrancyEffectView
    

    image of the final effect