Geppelt Geppelt - 5 months ago 18
Swift Question

Unable to call UIView from Class and cast though For loop

I have about a dozen

UIViews
that I want to add via a For loop cast. Currently setting it up and could not getting it working. Stepped back and tried to set it up for just a single
UIView
, and still no luck.

I get the error:


fatal error: unexpectedly found nil while unwrapping an Optional value


Any advice for what I am doing wrong would be appreciated:

Code:

class ViewController: UIViewController {

var button: HamburgerButton! = nil
var block1: shapeTestUI! = nil

override func viewDidLoad() {
super.viewDidLoad()
let block = createBlock(block1)
self.view.addSubview(block)
}

func createBlock(blocks:UIView) -> UIView {
let block = blocks as UIView
block.frame = CGRectMake(0, 0, 50, 50)
return block
}
}

Answer

You have to init block1 before you can pass it to createBlock since blocks function param isn't an optional :

override func viewDidLoad() {
    super.viewDidLoad()

    block1 = shapeTestUI() //Or any init from your shapeTestUI model

    let block = createBlock(block1)
    self.view.addSubview(block)


}