amckinley amckinley - 1 year ago 69
Swift Question

Moving a UIView while changing its nested UILabel causes the view to jump back to initial position

I'm trying to set up a UISlider so that when the slider is moved, a bubble appears over the thumb rectangle to show what the current value is set to.

Moving the view on its own works just fine, but when altering the value of the label inside that view, the label will quickly 'jump' back to the initial location that I placed the UIView on the storyboard when the slider hits certain points on the track. It then jumps back as soon as the thumb rectangle moves past that 1 pixel on the track.

I've made a sample project that replicates the issue here:

Alternatively, here's what my ViewController looks like.

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var bubble: UIView!
@IBOutlet weak var bubbleLabel: UILabel!

override func viewDidLoad() {

override func didReceiveMemoryWarning() {

@IBAction func sliderMoved(sender: UISlider) {
let sliderValue = lroundf(sender.value)

let trackRect = sender.trackRectForBounds(sender.frame)
let thumbRect = sender.thumbRectForBounds(sender.bounds, trackRect: trackRect, value: Float(sliderValue)) = thumbRect.midX

slider.value = Float(sliderValue)

// If this next line is commented, the jumping issue does not occur.
bubbleLabel.text = String(sliderValue)

Answer Source

Auto Layout is moving your bubble view back to the position that is specified by its constraints. Instead of changing the frame of the bubble view, create an @IBOutlet to the NSLayoutContraint that positions the bubble horizontally, and then alter the constant property of that constraint to move the bubble.