Reputation: 7
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: https://github.com/austinmckinley/SliderBubbleTest
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() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.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))
bubble.center.x = thumbRect.midX
slider.value = Float(sliderValue)
// If this next line is commented, the jumping issue does not occur.
bubbleLabel.text = String(sliderValue)
}
}
Upvotes: 0
Views: 405
Reputation: 154651
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.
If you make the horizontal constraint for the bubble to be: Bubble.CenterX == Superview.Leading
, and add the constraint outlet to your code:
@IBOutlet weak var bubbleCenterX: NSLayoutConstraint!
Then you just have to replace this:
bubble.center.x = thumbRect.midX
with:
bubbleCenterX.constant = thumbRect.midX
Upvotes: 1