0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift][CAGradientLayer]グラデーションに使用する色をUIColorのプロパティに設定する

Last updated at Posted at 2021-03-07

環境

Xcode12.0/Swift5

実装

ViewController.swift
import UIKit

extension UIColor {
    // グラデーションの開始色
    static let gradationStartColor = #colorLiteral(red: 1, green: 0.07205364853, blue: 0.1780711412, alpha: 1)
    // グラデーションの終了色
    static let gradationEndColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1)
}

class ViewController: UIViewController {

    @IBOutlet private weak var GradationView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [UIColor.gradationStartColor.cgColor, UIColor.gradationEndColor.cgColor]
        //グラデーションレイヤーをViewに合わせる
        gradientLayer.frame = GradationView.bounds
        //グラデーションレイヤーをビューの一番下に配置
        GradationView.layer.insertSublayer(gradientLayer, at: 0)
    }
}

Main.storyboard

スクリーンショット 2021-03-07 15.12.39.png

実行結果

mojikyo45_640-2.gif
  • (大規模な画面だと、AutoLayoutで設定したviewにグラデーションを設定する場合、プロパティにしないと上手くいかないことがある。)

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?