user3033437 user3033437 - 4 months ago 17
Swift Question

Custom UIView class allways crash when initialized

I've created a simple custom UIView class.

import Foundation
import UIKit

class customShop : UIView{

var bannerViewHight: NSLayoutConstraint!
var bannerViewTop: NSLayoutConstraint!
var bannerViewLeft: NSLayoutConstraint!
var bannerViewRight: NSLayoutConstraint!
var banerDiscount: UIImageView!
var bannerImageShop : UIImageView!
var bannerTitle : UILabel!
var bannerDescription: UILabel!
var bannerButton: UIButton!


override init (frame : CGRect) {
super.init(frame : frame)
self.bannerTitle.text = ""

}

convenience init () {
self.init(frame:CGRect.zero)
}

required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
}


I'm instantiating this way:

var mainView : customShop = customShop()
mainView.bannerTitle.text = "hola"
let desc = super.getLanguageFromDict(self.areaDetailValues.texts_description)


As you can see in the image, it crashes always when I try to set any value. How this can be?

enter image description here

Answer

As far as I can see, these are not outlets, and I don't see any initialisation code. What you should do is actually create that label via:

self.bannerTitle = UILabel()

or with frame so you are sure that you can see that label:

self.bannerTitle = UILabel(frame: frame)

second one will create the view with the size of the view.

I would suggest you to create xib file and connect outlets - it will be easier for you to maintain the view and see changes on the fly.

Comments