【问题标题】:Swift 3 - Auto scroll UITextView according to length of mp3Swift 3 - 根据 mp3 的长度自动滚动 UITextView
【发布时间】:2017-02-13 18:00:58
【问题描述】:

在我的 iOS 应用程序中,我在可滚动不可编辑的文本视图中播放 mp3 的歌词。我想根据每个 mp3 的长度自动滚动 textview。如何在 Swift 3 中做到这一点?

【问题讨论】:

  • 您是否尝试过使用Timer
  • 使用计时器并根据玩家的位置设置 UITextView 的滚动。
  • @nighttalker,你能详细说明一下吗?我想过使用计时器,但不知道如何根据歌曲的当前时间自动滚动文本视图
  • @新浪KH,请看我之前的评论

标签: ios swift scroll uitextview mp3


【解决方案1】:

您需要做的就是安排Timer 并计算在更新方法(选择器)中滚动的位置。

你班上的某个地方:

var timer = Timer()

func update() {
    // Assuming you're using an AVAudioPlayer, calculate how far along you are
    let progress = player.currentTime / player.duration

    // Get the number of characters
    let characters = textView.text.characters.count

    // Calculate where to scroll
    let location = Double(characters) * progress

    // Scroll the textView
    text.scrollRangeToVisible(NSRange(location: Int(location), length: 10))
}

然后,无论何时你想启动计时器:

timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(update), userInfo: nil, repeats: true)

歌曲播放完毕后,使计时器无效。

【讨论】:

  • 很好的答案!只是想知道,这不会与歌词同步,因为它们不一定会以恒定的速度流动。他可能必须用歌词或其他东西制作一个时间戳标记库,以便文本与声音精确同步
  • 感谢它的工作!是的,@Antoine 是对的,滚动与歌词不同步。我没有想到这一点。我不认为它会像我想象的那样工作。还是谢谢
  • 寻歌时滑块值增大如何处理?有什么解决办法吗?
【解决方案2】:

你可以设置 contentOffset:

func autoScroll() {
    let progress = currentTime / duration
    let contentOffset = CGPoint(x: 0.0, y: textView.contentSize.height * progress)
    textView.setContentOffset(contentOffset, animated: true)
}

并启动计时器:

let timer = Timer(timeInterval: 0.5, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .commonModes)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    相关资源
    最近更新 更多