user3722523
user3722523

Reputation: 1790

Init custom class UIVIew

Trying to init my custom class UIVIew with a xib file but crashed when trying to initialize properties :

import Foundation
import UIKit

class ReportView: UIView {

@IBOutlet weak var textView: UITextView!

override init (frame : CGRect) {
    super.init(frame : frame)

}

convenience init () {
    self.init(frame:CGRectZero)
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    addBehavior()
}

func addBehavior (){
    textView.layer.borderWidth = 1.0
    textView.layer.borderColor = UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 0.5).CGColor
    textView.layer.opacity = 0.9
    textView.layer.cornerRadius = 3
    textView.clipsToBounds = true
}
}

crashed on textview : fatal error: unexpectedly found nil while unwrapping an Optional value

Upvotes: 0

Views: 878

Answers (1)

Sulthan
Sulthan

Reputation: 130072

There are two possible problems depending on how your xib looks like:

  1. Either your outlet is not connected to the xib.

  2. Or the outlet is not available during initialization, so you cannot access textView which is still nil. The correct approach then is to override awakeFromNib method and put addBehavior there.

Upvotes: 2

Related Questions