Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extended UIView class using Swift

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)

like image 696
Aggressor Avatar asked Oct 07 '14 20:10

Aggressor


1 Answers

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.

like image 160
Mundi Avatar answered Oct 02 '22 04:10

Mundi