Created
February 23, 2020 13:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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