Nick
Nick

Reputation: 1444

Gradient background iPhone dimensions on iPad

I have a problem setting gradient background on iPad. On iPhones everything is ok but when I use iPad the gradient background has iPhone dimensions.

This is the problem

The code that I use to make the gradient is the on below.

func setGradientToTableView(tableView: UITableView) {

        let gradientBackgroundColors = [UIColor(red: 190.0/255.0, green: 219.0/255.0, blue: 0.0/255.0, alpha: 1).cgColor, UIColor(red: 13.0/255.0, green: 227.0/255.0, blue: 97.0/255.0, alpha: 1).cgColor]

        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = gradientBackgroundColors
        gradientLayer.startPoint = CGPoint(x: 0,y: 0)

        gradientLayer.frame = tableView.bounds
        let backgroundView = UIView(frame: tableView.bounds)
        backgroundView.layer.insertSublayer(gradientLayer, at: 0)
        tableView.backgroundView = backgroundView
    }

Upvotes: 1

Views: 67

Answers (2)

Michcio
Michcio

Reputation: 2876

You need to set frame for layer in viewDidLayoutSubviews:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableView.backgroundView?.layer.sublayers?.forEach { $0.frame = tableView.bounds }
    }

Also, as @Jan Schlorf suggests in comment, you can store your layer as property:

    lazy var gradientLayer = CAGradientLayer()

    //...

    func setGradientToTableView(tableView: UITableView) {
        let gradientBackgroundColors = [UIColor(red: 190.0/255.0, green: 219.0/255.0, blue: 0.0/255.0, alpha: 1).cgColor, UIColor(red: 13.0/255.0, green: 227.0/255.0, blue: 97.0/255.0, alpha: 1).cgColor]

        gradientLayer.colors = gradientBackgroundColors
        gradientLayer.startPoint = CGPoint(x: 0,y: 0)

        gradientLayer.frame = tableView.bounds
        let backgroundView = UIView(frame: tableView.bounds)
        backgroundView.layer.insertSublayer(gradientLayer, at: 0)
        tableView.backgroundView = backgroundView
    }

    //...

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        gradientLayer.frame = tableView.bounds
    }

Upvotes: 3

Chris
Chris

Reputation: 8091

I assume you didn't use autolayout?

Check your tableviewsize when starting your app with iPad Simulator. I think it is not as big as you think it is.

Upvotes: -1

Related Questions