7

I have been trying to subclass a UIView and using the help of https://stackoverflow.com/a/24036440/3324388 to handle the 'init(coder)' issue

However I keep running into snags with even the most basic attempts I'm hoping someone could post a simple example of the actual code needed to subclass a UIView with Swift.

My current code is

//image class
import UIKit

class childView: UIView {


    var image:UIImage!

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

}

I do not want to pass this NSCoder object (I'm not sure what it does and it makes my code messy). Could you post an example of how to cleanly subclass a UIView and then how you would initialize it in another class?

I'd really love to extend my UIView classes to have some cool effects like drop shadows, auto scaling, and lots of other goods without having to create subviews to handle all that (like UIImageViews inside UIScrollViews)

Community
  • 1
  • 1
Aggressor
  • 13,323
  • 24
  • 103
  • 182

1 Answers1

12

Seems really simple. Just following the code completion.

class MyView : UIView {

    var image = UIImage()

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

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

var v = MyView()

I am initializing a dummy UIImage so you won't have an ugly surprise if you use your unwrapped version if it is nil.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • How does this work with the override and the required? When is the required one called? – Aggressor Oct 07 '14 at 21:35
  • 1
    When the parameters fit the signature – JustSid Oct 07 '14 at 21:44
  • Ok great, I think I was getting confused between the required vs the override. Thank you. – Aggressor Oct 07 '14 at 21:50
  • Helpful but passively insulting at the same time. Why not just help? Those who are learners don't need judgmental comments like this "Cannot imagine what the problem is..." One up vote, and one down vote. – drew.. Feb 15 '18 at 13:28