Useful extensions for UIView

阴凯歌
2023-12-01

UITextField Shaking

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")
    }
}

Round UIImageView

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

Convenient way to fake a blur background with image

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)
    }
}

Enable scrollsToTop for multiple scrollviews

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
    }
}
 类似资料:

相关阅读

相关文章

相关问答