15
9

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 5 years have passed since last update.

テコテックAdvent Calendar 2018

Day 11

Swift UIViewの一部を角丸にしたい

Posted at

UIViewの一部を角丸にしたい

この記事は、TECOTEC Advent Calendar 2018 の11日目の記事です。

ソースコード

開発環境:Xcode:10.1
開発言語:Swift4.2

【UIView.layer.maskedCornersに設定できる値(iOS11以降)】
.layerMinXMinYCorner 左上
.layerMaxXMinYCorner 右上
.layerMinXMaxYCorner 左下
.layerMaxXMaxYCorner 右下

【UIBezierPathのbyRoundingCornersに設定できる値(iOS11未満)】
.topLeft 左上
.topRight 右上
.bottomLeft 左下
.bottomRight 右下
.allCorners 全て

※ autoLayoutを使用しているとiOS11未満の角丸処理がviewDidLoad()だと上手くいかない可能性があるのでviewDidAppear()以降で書くと安全

sample1.swift
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var yellowView: UIView!
    @IBOutlet weak var blueView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        /// iOS11以降の角丸処理
        blueView.layer.cornerRadius = 20
        blueView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner]
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        /// iOS11未満の角丸処理
        let path = UIBezierPath(roundedRect:yellowView.bounds,
                                byRoundingCorners:[.topRight, .bottomRight],
                                cornerRadii: CGSize(width: 20, height: 20))
        let maskLayer = CAShapeLayer()
        maskLayer.path = path.cgPath
        yellowView.layer.mask = maskLayer
    }
}

上記ソースを実行するとこんな感じ
Simulator Screen Shot - iPhone XS Max - 2018-12-12 at 19.24.44.png

・感想
 iOS11以降の角丸処理簡単になったなあ

15
9
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
15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?