0

I am trying to create a custom UIView class that I can change the class for some views in my app. I want the view to be round and have the blur effect. I can get it to work via func that specifically references the outlet name but would like to just change the class of the view so it is reuseable.

import UIKit

class RoundedBlur: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addRoundedBlur()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.addRoundedBlur()
    }

    func addRoundedBlur() {
        let roundedBlurView = UIView()

        let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light))
        blur.frame = roundedBlurView.bounds
        blur.layer.cornerRadius = 0.5 * roundedBlurView.bounds.size.width
        blur.clipsToBounds = true

        blur.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        roundedBlurView.insertSubview(blur, at: 0)
    }
}
Miknash
  • 7,888
  • 3
  • 34
  • 46

1 Answers1

0

You don't need to create a subview to achieve this. You can just reference the class itself, this way you can create new views by extending reusing this one.

class RoundedBlur: UIView {

  override init(frame: CGRect) {
    super.init(frame: frame)
    self.addRoundedBlur()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.addRoundedBlur()
  }

  func addRoundedBlur() {
    let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light))
    self.frame = self.bounds
    self.layer.cornerRadius = 10.0
    self.clipsToBounds = true

    blur.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.insertSubview(blur, at: 0)

  }
}
Henrique B.
  • 450
  • 3
  • 9