2017-02-13 23 views
0

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

+0

您是否尝试过使用'Timer'? – nighttalker

+0

使用计时器并根据玩家的位置设置UITextView的滚动条。 –

+0

@nighttalker,你可以详细说明一下吗?我想过使用计时器,但不知道如何根据歌曲的当前时间自动滚动文本视图 – SergeH

回答

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) 

当歌曲结束时,无效计时器。

+1

很好的回答!只是想知道,这不会与歌词同步,但因为它们不一定会以恒定的速度流动。他可能需要制作一个带有歌词的时间戳记标记库,以便文本能够精确地与声音同步 – Antoine

+0

谢谢!是的@Antoine是对的,滚动没有与歌词同步。我没有想到通过。我不认为它会像我想象的那样工作。不管怎么说,多谢拉 – SergeH

0

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