在我的iOS应用程序中,我在可滚动的不可编辑的文本视图中播放mp3的歌词。我想根据每个mp3的长度自动滚动文本视图。如何在 Swift 3 中做到这一点?
您需要做的就是安排一个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)
歌曲结束后,使计时器失效。
您可以设置 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)