Reputation: 666
I have a class of UITableViewCell and that cell is intialized from another class that contains table view.I want to pass an integer value to cell class from tableview class.
In objective c it was simply done by making global variable and passing values when making instance of global variable class. I do not want any value at declaration time and this global variable will change the value and get the value when it is passing by another class.
I do not know where is mistake please see my code mentioned below-
UITableViewCell class :-
import UIKit
class PostHeaderCell: UITableViewCell {
var loopVariable: Int? // This is global variable that i have written
@IBOutlet weak var viewMain: UIView!
@IBOutlet weak var viewCategory: UIView!
@IBOutlet weak var mainViewHeight: NSLayoutConstraint!
@IBOutlet weak var topLayoutViewCategory: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
print(loopVariable)
viewMain.layer.cornerRadius=5.0
viewMain.layer.borderColor = UIColor(red: 212.0/255.0, green: 217.0/255.0, blue: 221.0/255.0, alpha: 1.0).CGColor
viewMain.layer.borderWidth=1.0
var myVar = 50.0 as CGFloat
for var i=0;i<loopVariable;i++
{
mainViewHeight.constant=mainViewHeight.constant+30
var postCell :PostCategoryView?
postCell = NSBundle.mainBundle().loadNibNamed("PostCategoryView", owner: self, options: nil)[0] as? PostCategoryView
postCell!.frame=CGRectMake(10,myVar+10,postCell!.frame.size.width,50)
print(postCell)
myVar = myVar + 55.0;
}
self.layoutSubviews()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Now, I implemented this UITableViewCell class in another class and passing loop variable value from that class, Please look below mentioned code for calling and instantiating PostHeaderCell- Class B:-
var cell:PostHeaderCell! = tableView.dequeueReusableCellWithIdentifier("PostHeaderCell", forIndexPath: indexPath) as! PostHeaderCell
cell.loopVariable=2
return cell
Note -: I want to initialise the value of loop variable from Class B but it always give nil ( i have passed 2 as a value for loopVariable).
Upvotes: 2
Views: 1330
Reputation: 70165
What you need is a 'class' variable, declare with static
. Here is a simplified example:
class Foo {
static var counter : Int = 0
init () {
Foo.counter++
}
}
In this example, everytime you create a new Foo
the counter gets incremented. As such:
9> Foo()
$R0: Foo = {}
10> Foo.counter
$R1: Int = 1
11> Foo()
$R2: Foo = {}
12> Foo.counter
$R3: Int = 2
But, the increment is just an example of how the counter value is scoped to the class, not to an instance.
For your case, you can assign the counter
with
Foo.counter = 10
and you can use it within other functions:
class Foo {
// ...
func awakeFromNib () {
for var i = 0; i < Foo.counter; i++ {
// ...
}
}
}
Upvotes: 1