user3033437 user3033437 - 1 year ago 146
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 () {

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download