Feels like typing wrong passcode on lock screen
extension UITextField {
func tm_shake() {
let anim = CAKeyframeAnimation(keyPath: "position.x")
anim.values = [0, 10, -10, 10, 0]
anim.keyTimes = [0, 1/6.0, 0.5, 5/6.0, 1]
anim.duration = 0.4
anim.additive = true
self.layer.addAnimation(anim, forKey: "shake")
}
}
Might be a dumb way to make UIIMageView round, but it works well
extension UIImageView {
func roundSquareImageView() {
let radius = self.frame.width/2
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
}
Scenario: I want to make a transparent background with little blur effect on a pushed viewcontroller, I would take a screen shot on parent viewcontroller, use it as background image and make this image blur
extension UIView {
func convertViewToImage() -> UIImage {
return self.convertViewToImage(self.bounds)
}
// take screen shot
func convertViewToImage(frame: CGRect) -> UIImage {
UIGraphicsBeginImageContext(frame.size)
self.drawViewHierarchyInRect(frame, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func addBlurBackgroundViewWithImage(image: UIImage?, frame: CGRect, style: UIBlurEffectStyle) {
let blurEffect = UIBlurEffect(style: style)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = frame
let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)
let vibrancyView = UIVisualEffectView(effect: vibrancyEffect)
vibrancyView.frame = frame
blurView.addSubview(vibrancyView)
let backgroundImageView = UIImageView(frame: frame)
backgroundImageView.image = image
backgroundImageView.contentMode = UIViewContentMode.ScaleAspectFit
self.insertSubview(backgroundImageView, atIndex: 0)
self.insertSubview(blurView, atIndex: 1)
}
}
If there are multiple scrollviews in one viewcontroller and all of them enable property scrollsToTop by default, this feature would not work properly. Here we disable this property for all of the subviews but one we need to enable.
extension UIView {
func enableScrollsToTop(parentView: UIView, scrollView: UIScrollView) {
for subView in parentView.subviews {
if let view = subView as? UIView {
// recursion
view.enableScrollsToTop(subView as! UIView, scrollView: scrollView)
if let subScrollView = view as? UIScrollView {
subScrollView.scrollsToTop = false
}
}
}
scrollView.scrollsToTop = true
}
}