在我的iOS应用程序中,我在mp3的歌词里面,我正在可滚动的不可编辑的文本视图中播放。我想根据每个mp3的长度自动滚动textview。我怎么能在Swift 3中做到这一点?
答案 0 :(得分:2)
您需要做的就是安排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)
歌曲播放完毕后,定时器无效。
答案 1 :(得分:1)
您可以设置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)