Do the following:
Create a class called A
, subclass of UITableViewCell
:
class A: UITableViewCell {
var isChosen: Bool = true
}
Create a xib file and drag a UITableViewCell
object as the top level object, and make sure to set its class to A
:
Create an instance of A
:
var a = NSBundle.mainBundle().loadNibNamed("A", owner: nil, options: nil)[0] as A
Print isChosen
:
println(a.isChosen)
Output:
false
Why is this happening? It only happens when you initialize the instance from a nib.
Even if you declare the variable as an optional and set it to nil
:
var isChosen: Bool! = nil
it'll still be set to false
somehow.
Since your class A
does not have any init methods defined swift automatically generated default initializer for you. With default init()
method code var isChosen: Bool = true
is a shortcut to:
class A: UITableViewCell {
var isChosen: Bool
init() {
isChosen = true
}
}
When you create your custom cell of type A
from Nib then auto generated init()
method does not get called because initWithCoder
called hence isChosen
value is false
.
UPDATE:
As already mentioned by @MattGibson in comments to the question, with xCode 6 Beta 5 update we can address the problem. It can be solved by adding init with coder
initializer and marking it as required, so A
should contain code bellow:
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
How it works? From Beta 5 Release Notes:
The required modifier is written before every subclass implementation of a required initializer. Required initializers can be satisfied by automatically inherited initializers.
UPDATE:
required init(coder aDecoder: NSCoder!) { ... }
should be added only if you override at lest one init
method in your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With