在更改其嵌套的UILabel时移动UIView会导致视图跳回到初始位置

时间:2016-06-22 16:47:53

标签: ios iphone swift uiview

我正在尝试设置一个UISlider,以便在移动滑块时,拇指矩形上会出现一个气泡,以显示当前值的设置。

移动视图本身就可以正常工作,但是当更改该视图中标签的值时,标签会快速“跳转”回到初始位置,当滑块达到某个位置时,我将UIView放在故事板上在赛道上的点。一旦拇指矩形移过轨道上的1个像素,它就会跳回来。

我已经制作了一个示例项目,可以在此复制问题:https://github.com/austinmckinley/SliderBubbleTest

或者,这是我的ViewController的样子。

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)
    }
}

1 个答案:

答案 0 :(得分:1)

自动布局正在将气泡视图移回其约束条件指定的位置。不要更改气泡视图的框架,而是为@IBOutlet创建一个水平定位气泡的NSLayoutContraint,然后更改该约束的constant属性以移动气泡。

如果您将气泡的水平约束设为:Bubble.CenterX == Superview.Leading,并将约束插座添加到您的代码中:

@IBOutlet weak var bubbleCenterX: NSLayoutConstraint!

然后你只需要替换它:

bubble.center.x = thumbRect.midX

使用:

bubbleCenterX.constant = thumbRect.midX