更改UILabel的文本会导致scrollview跳转

时间:2017-04-27 18:17:37

标签: ios swift uiscrollview uilabel

我使用计时器来更新UILabel的文本属性。 UILabel处于垂直UIScrollView。

static func play() {
        timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.timerUpdate), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .commonModes)
    }

@objc private static func timerUpdate(_ timer: Timer) {
        let progress = AudioManager.currentTime
        NotificationCenter.default.post(name: NSNotification.Name("didUpdateProgress"), object: self, userInfo: ["progress":progress])
    }

调用下一个函数时,将使用新字符串更新currentTimeLabel.text。

func didUpdateProgress(_ notification: Notification) {
        if let progress = notification.userInfo?["progress"] as? Float {
            slider.setValue(progress, animated: true)
            currentTimeLabel.text = String(format: "%01i:%02i", Int(progress/60), Int(progress) % 60)
        }
    }

但是如果scrollview不在其初始位置,即contentOffset不为零,则每次currentTimeLabel.text更改时,scrollView都会跳转。我想,明确设置这个特定标签的高度限制将解决这个问题,但它并没有:(

如何使用UILcrollView中的UILabel文本更新计时器,以便scrollview不会跳转?

3 个答案:

答案 0 :(得分:2)

我所描述的问题出在我的viewDidLayoutSubviews()方法中。每次视图出现在屏幕上时,我都希望scrollview重置其位置。所以我这样做了

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    scrollView.setContentOffset(.zero, animated: false)
}

我不知道每次更改标签的文本属性时都会调用此方法。嗯,现在看起来非常清楚,因为更改文本会使标签重新计算其宽度,但在开始时它并不是那么明显:)

抱歉,我错过了这个问题。为了避免不必要的细节并尽量减少问题,很容易省略重要的事情,特别是如果你真的不知道问题的位置。

答案 1 :(得分:0)

我在使用scrollView时遵循这种做法。 如果您想使用ScrollView,可以按照此操作。

  1. 使用scrollView并自动布局top,left,bottom,right 0约束到superview(主视图)

  2. 获取另一个视图,它将是您的容器视图并执行上述自动布局(0约束)

  3. 放置所需的插座并确保已将所有约束最重要的顶部和底部约束拉到每个插座。如果它需要高度,则给出特定的高度。

  4. enter image description here

    1. 这一点应该是一个。:)让您的视图高度更大,以便您可以放置​​所需的插座,一切都将清晰。
    2. enter image description here

      因此,当我像这样编写代码时,我发现没有什么不寻常的。那就是跳。应该再试一次。

      class ViewController: UIViewController {
      @IBOutlet weak var label1: UILabel!
      @IBOutlet weak var label2: UILabel!
      var timer:Timer!
      override func viewDidLoad() {
          super.viewDidLoad()
          // Do any additional setup after loading the view, typically from a nib.
      
          timer = Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(self.onTimerUpdate), userInfo: nil, repeats: false)
      }
      
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
      
      func  onTimerUpdate() {
          self.label1.text = "I have changed"
      }
      

      }

      我将scrollView拉到底部,4秒后标签文字已经更改。

答案 2 :(得分:0)

设置文本可能会更改UILabel的内在内容大小。如果UILabel属性numberOfLines定义为0(默认值),则允许其根据内容增长。在这种情况下,设置文本时UILabel高度可能会缩小/增大。如果您根据内在内容大小另外指定了自动布局约束,则可能会影响滚动视图行为。我不太确定。

请查看或提供其他信息:

  • UIScrollView& UILabel自动布局约束
  • UILabel属性(numberOfLines = 0?)
相关问题