John Doe John Doe - 6 months ago 57
iOS Question

Where do I put common utility functions in iOS 8 + Swift

I have the following method (for instance) that I'd like to be able to use from any ViewController in an iOS + Swift project:

func initializeBlurEffectOnGivenUIView(UIViewToBeBlurred: UIView) {

let UIViewToBeBlurredHeight = UIViewToBeBlurred.frame.size.height
let UIViewToBeBlurredWidth = UIViewToBeBlurred.frame.size.width
let UIViewToBeBlurredX = UIViewToBeBlurred.frame.origin.x
let UIViewToBeBlurredY = UIViewToBeBlurred.frame.origin.y

let blurEffect:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)

let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
let blurEffectView:UIVisualEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = CGRectMake(UIViewToBeBlurredX, UIViewToBeBlurredY, UIViewToBeBlurredWidth, UIViewToBeBlurredHeight)
blurEffectView.contentView.addSubview(vibrancyEffectView)

UIViewToBeBlurred.addSubview(blurEffectView)
}


I have more common helpers such as there that I'd like to make available as well. How do I structure the application to achieve this?

Answer

Use an extension, like this:

extension UIView {
    func initializeBlurEffect() {

        let height = self.frame.size.height
        let width = self.frame.size.width
        let x = self.frame.origin.x
        let y = self.frame.origin.y

        let blurEffect:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)

        let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
        let blurEffectView:UIVisualEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = CGRectMake(x, y, width, height)
        blurEffectView.contentView.addSubview(vibrancyEffectView)

        self.addSubview(blurEffectView)
    }
}

Then call it like this:

myview.initializeBlurEffect()
Comments