【问题标题】:Moving a UIView while changing its nested UILabel causes the view to jump back to initial position在更改其嵌套的 UILabel 时移动 UIView 会导致视图跳回初始位置
【发布时间】:2016-06-22 16:47:53
【问题描述】:

我正在尝试设置 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)
    }
}

【问题讨论】:

    标签: ios iphone swift uiview


    【解决方案1】:

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

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

    @IBOutlet weak var bubbleCenterX: NSLayoutConstraint!
    

    那么你只需要替换这个:

    bubble.center.x = thumbRect.midX
    

    与:

    bubbleCenterX.constant = thumbRect.midX
    

    【讨论】:

    • 好像已经解决了,谢谢!任何想法为什么这个问题只发生在更改标签的文本时?
    • 更改标签的文本会触发自动布局的重新布局。我不知道为什么会这样,但其他事情也可以触发布局,所以最好不要在自动布局控制下通过改变它们的框架来重新定位项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 2011-07-16
    • 2011-12-08
    相关资源
    最近更新 更多