Add CAGradientLayer to view

Seba

New Member
#1
I have this custom UIView
Mã:
import UIKit

class LoginView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupBackground()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupBackground()
    }

    private func setupBackground() {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [
            UIColor(r: 0, g: 17, b: 214).cgColor,
            UIColor(r: 0, g: 9, b: 119).cgColor
        ]
        gradientLayer.locations = [0, 1]
        gradientLayer.frame = bounds

        layer.addSublayer(gradientLayer)
    }
}
And this is my UIViewController
Mã:
import UIKit

class LoginController: UIViewController {

    let loginView = LoginView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view = loginView
    }

    override var preferredStatusBarStyle : UIStatusBarStyle {
        return .lightContent
    }
}
The problem is that the GradientLayer doesn't show on the screen, the background is still black.

Thanks for the help!
 

Admin

Administrator
Thành viên BQT
#2
If you like to use in viewDidLoad (Load once), just declare your custom view inside like following code:
Mã:
override func viewDidLoad() {
    super.viewDidLoad()
    let loginView = LoginView(frame: self.view.bounds)
    self.view = loginView
}
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top