remy boys remy boys - 2 years ago 98
Swift Question

UILabel shifts to left when UITableView Loads and gets fix after scrolling

i have a tableView where i putted a UILabel and am changing its left Constraint's Constant dynamically :
my TableViewController

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? TableViewCell

//let totalLength = (cell.slider.frame.width + (cell.postNumber.frame.width + cell.negNumber.frame.width + cell.middleConstraint.constant))
let differnceToRemove = (cell!.postNumber.frame.width + cell!.negNumber.frame.width + cell!.middleConstraint.constant) / 2

if indexPath.row == 0 {
cell!.slider.value = 0

}else if indexPath.row == 1 {
cell!.slider.value = 1.0
else if indexPath.row == 2 {
cell!.slider.value = 0.5
else if indexPath.row == 3 {

cell!.slider.value = 0.25
else if indexPath.row == 4 {
cell!.slider.value = 0.33

cell!.contraint.constant = ((( CGFloat (cell!.slider.value) ) * cell!.slider.frame.width) + cell!.paddingConstraint.constant) - differnceToRemove

let leftTrackImage = UIImage(named: "vLine")
cell!.slider.setThumbImage(leftTrackImage, forState: .Normal)
cell!.slider.setThumbImage(leftTrackImage, forState: .Selected)
cell!.slider.setThumbImage(leftTrackImage, forState: .Highlighted)

return cell!

my TableViewCell:

class TableViewCell: UITableViewCell {

@IBOutlet var paddingConstraint: NSLayoutConstraint!
@IBOutlet var postNumber: UILabel!
@IBOutlet var negNumber: UILabel!
@IBOutlet var middleConstraint: NSLayoutConstraint!

@IBOutlet var contraint: NSLayoutConstraint!

@IBOutlet var slider: CustomSlider!

override func awakeFromNib() {
// Initialization code

image 1 when tableView Loads : image 1 when View loads

image 2 when i scroll ones through it :

image 2 after scrolling

after scrolling on my tableView every labels set on to their exact position , tried so many things like re arranging my Constraints in story board , clean build etc still no luck if anybody knows whats wrong then please do help

Answer Source

You need to update the layout after changing the constraint:

cell!.contraint.constant =  ((( CGFloat (cell!.slider.value) ) * cell!.slider.frame.width) + cell!.paddingConstraint.constant) - differnceToRemove

See the "Laying out Subviews" section of the UIView Class Reference document.

Auto Layout can be tricky, so I am referencing Apple's guide here.


You could also use these methods in viewDidLoad().


We are forcing the table view to reload it's self and thus do another layout pass. This is a work around you still should workout what is the difference between the first layout pass and the second (due to you scrolling). I would start with your custom table view cell.

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