How to apply constraints to controls of UITableViewCell programatically ?

Hello

In my code i am having problem to change position of label added in cell after changing orientation. In my case after reloading tableview, it insert another value in cell instead of changing position of old lable.

here is my code:-

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

var contactName = ["Aman","Amit","Saman","Sumit"]

var tableView = UITableView()

var w = UIScreen.mainScreen().bounds.width

override func viewDidLoad() {

super.viewDidLoad()

/

tableView.frame = CGRectMake(0,60,w,w)

tableView.dataSource = self

tableView.delegate = self

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

self.view.addSubview(tableView)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int

{

return 1

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

{

return contactName.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

{

var w = UIScreen.mainScreen().bounds.width

var h = UIScreen.mainScreen().bounds.height

var demo = UILabel()

var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell

demo.frame = CGRectMake(w-100,0,100,30)

demo.text = contactName[indexPath.row]

cell.addSubview(demo)

return cell

}


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

return 65

}

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)

{

dispatch_async(dispatch_get_main_queue()) {

var h = self.view.bounds.size.height

var w = self.view.frame.size.width

self.tableView.frame = CGRectMake(0,60,w,w)

/

}

}

}

You shouldn't add subviews in cellForRowAtIndexPath because table view is reusing cells so you might get a cell which allready has demo label as a subview. Instead add the label in your custom cell's awakeFromNib method.

How to apply constraints to controls of UITableViewCell programatically ?
 
 
Q