0
0

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 1 year has passed since last update.

UILabelの背景をグラデーションさせる

Posted at

概要

UILabelの背景にグラデーションを設定する時のメモです。

実装

カスタムのUILabelを作成しました。
以下のコードでラベルにグラデーションを設定できます。
画像のような感じになります。

また、ラベルの周りに適当なサイズの余白を加えました。

GradationLabel.swift
class GradientLabel: UILabel {
    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        translatesAutoresizingMaskIntoConstraints = false
        textAlignment = .center
        textColor = .white
        text = "hoge"
        
        if let gradientLayer = layer as? CAGradientLayer {
            gradientLayer.colors = [
                UIColor.systemPurple.cgColor,
                UIColor.systemPink.cgColor,
            ]
            gradientLayer.startPoint = CGPoint(x: 0, y: 0)
            gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        }
        
        layer.cornerRadius = 2
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var intrinsicContentSize: CGSize {
        var intrinsicContentSize = super.intrinsicContentSize
        intrinsicContentSize.height += 4
        intrinsicContentSize.width += 4
        return intrinsicContentSize
    }
}

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?