user1218464 user1218464 -4 years ago 441
Objective-C Question

UITableViewCell awakeFromNib wrong frame size

I have a UITableViewCell with constraints so that the cells layout correctly on iPhone 6 and iPhone 6+.

The cell contents correctly resize correctly. However, I need to draw a sublayer gradient over one of the views inside. In order to do so, I'm using awakeFromNib to draw the sublayer.

AwakeFromNib is giving the size of the frame prior to it autoresizing and therefore the gradient subview isn't the right size.

If I use layoutSubviews, the first time it's called, the size is also wrong and the cell needs to be scrolled before it has the right size; so that method also isn't working

What method should I be using to get the right frame size in order to draw correctly?

Answer Source

This code worked for me, is written in Swift.

import UIKit
import QuartzCore

class DemoTableViewCell: UITableViewCell {
    @IBOutlet weak var gradientView: UIView!

    private let gl = CAGradientLayer()

    override func awakeFromNib() {

        // set gradient
        let colors: [AnyObject] = [
            UIColor(white: 0, alpha: 0.8).CGColor
        gl.colors = colors
        gradientView.layer.insertSublayer(gl, atIndex: 0)

    override func layoutSubviews() {

        // update gradient
        gl.frame = gradientView.bounds
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download