【问题标题】:How to repeat the animation when scrolling the TextView with Swift?使用 Swift 滚动 TextView 时如何重复动画?
【发布时间】:2018-04-09 04:39:30
【问题描述】:

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)
    }

}

这是它的样子:

当 TextView 滚动到底部时动画将停止。但我希望它一次又一次地重复滚动。有什么办法让它工作吗?任何建议将不胜感激。

【问题讨论】:

  • 在 startScrolling 方法上只需设置 txtViewStory.contentOffset.y + txtViewStory.bounds.heigt == txtViewStory.contentSize.height 之类的条件并重置内容偏移量
  • 谢谢,乔恩。我是斯威夫特的新手。能不能说的详细点?

标签: ios swift uiscrollview uitextview


【解决方案1】:

非常脏的代码,但应该可以工作;>

@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()

}

【讨论】:

  • 谢谢,米哈乌。但是好像不行,添加“scrollingTimer = nil”的时候会报错:nil cannot be assigned to type 'Timer'。滚动到底部时它会停止。
  • 因此删除该行或将计时器更改为可选
  • 是的,我尝试删除它。删除线不会重复滚动到底部。
  • 哦,是的,它不会 - 它会在按钮单击后恢复
  • 谢谢。迈克尔。是的,它会在单击按钮时恢复。您能否分享一些关于如何一遍又一遍地重复滚动 textView 的想法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
相关资源
最近更新 更多