如何使用Swift滚动TextView时重复动画?

时间:2017-10-27 14:23:51

标签: ios swift uiscrollview uitextview

Swift 4:我点击按钮时尝试滚动textView。这是我的代码:

import UIKit



class ViewController: UIViewController {

    @IBOutlet weak var txtViewStory: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }


    var scrollingTimer = Timer()

    @IBAction func scroll(_ sender: UIButton) {
        scrollingTimer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(ViewController.startScrolling), userInfo: nil, repeats: true)

        scrollingTimer.fire()

    }

    @objc func startScrolling(){
        var currentOffset = txtViewStory.contentOffset
        currentOffset = CGPoint(x: currentOffset.x, y: currentOffset.y + 1)
        txtViewStory.setContentOffset(currentOffset, animated: false)
    }

}

以下是它的样子:

Gif1

当TextView滚动到底部时,动画将停止。但我希望它能一次又一次地重复滚动。有没有办法让它发挥作用?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

非常脏的代码但应该有用;>

@IBAction func scroll(_ sender: UIButton) {
    scrollingTimer.invaldiate()
    scrollingTimer = nil
    txtViewStory.setContentOffset(CGPoint(x: currentOffset.x, y: 0), animated: false)

    scrollingTimer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(ViewController.startScrolling), userInfo: nil, repeats: true)
    scrollingTimer.fire()

}