Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

init UIView with arguments?

Tags:

swift

My UIView looks like this :

  override init (frame : CGRect)
    {

        super.init(frame : frame)

    }

I would like to add an argument such as :

 override init (frame : CGRect, number:Int)

What is the right way to do it so I can init and send arg in one line ?

like image 812
Curnelious Avatar asked Aug 28 '26 19:08

Curnelious


1 Answers

You would define your class something like this:

class MyView: UIView {
    let number: Int

    init(frame: CGRect, number: Int) {
        self.number = number

        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        // Need to initialize the number property here. Do so appropriately.
        super.init(coder: aDecoder)
    }
}

The use of the number property is just an example. Do what you actually need.

And you would create an instance like this:

let mv = MyView(frame: .zero, number: 42)

Obviously you would pass a useful frame.

like image 59
rmaddy Avatar answered Aug 30 '26 10:08

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!