Swift 3 - 根据 mp3 的长度自动滚动 UITextView

Swift 3 - Auto scroll UITextView according to length of mp3

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

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

你的某处 class:

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)

歌曲结束后,使计时器失效。

您可以设置 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)