init UIView with arguments?

Viewed 5830

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 ?

2 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.

You can do something like this:

class CustomView: UIView{

var number: Int

init(frame : CGRect, number: Int) {

    self.number = number
    print("Number = \(number)")
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")

   }

}

Then add it to the stack like so:

  let viewToAdd = CustomView(frame: CGRect(x: 20, y: 72, width: 100 , height: 100), number: 1)
  viewToAdd.backgroundColor = .red
  self.view.addSubview(viewToAdd)
Related