2017-02-13 48 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)