Skip to content

Instantly share code, notes, and snippets.

@hanishassim
Created February 23, 2020 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanishassim/40c720daffd83cf2b4b0d7e7210f93be to your computer and use it in GitHub Desktop.
Save hanishassim/40c720daffd83cf2b4b0d7e7210f93be to your computer and use it in GitHub Desktop.
Superclass to create a smooth rounded UIView, works for animated rounded view too
//
// SmoothedView.swift
//
// Created by H on 23/02/2020.
// Copyright © 2020 H. All rights reserved.
//
import UIKit
final class SmoothedView: UIView {
var cornerRadius: CGFloat = 20.0
private lazy var maskLayer: CAShapeLayer = {
self.layer.mask = $0
return $0
}(CAShapeLayer())
override var bounds: CGRect {
set {
super.bounds = newValue
// Update the frame of the mask with the new bounds
maskLayer.frame = newValue
// Update the path of the mask with the new bounds
let newPath = UIBezierPath(roundedRect: newValue, cornerRadius: cornerRadius).cgPath
// If the bounds change is animated, copy the animation to mimic the timings
if let animation = self.layer.animation(forKey: "bounds.size")?.copy() as? CABasicAnimation {
animation.keyPath = "path"
animation.fromValue = maskLayer.path
animation.toValue = newPath
maskLayer.path = newPath
maskLayer.add(animation, forKey: "path")
} else {
maskLayer.path = newPath
}
}
get { return super.bounds }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment