在一定时间内从UITextView更改文本

时间:2017-08-15 21:15:55

标签: swift uitextview

我有UITextView,我想要做的是在2秒后添加不同的文字。因此,每2秒钟文本将消失,另一个文本将出现。我只用了2个文本就完成了这个,但如果我想拥有更多文本,那该怎么办呢?

以下代码将向您展示我是如何做到的:

@IBOutlet weak var label: UILabel!

var isTextOne = true
var textOne: String = "one"
var textTwo: String = "two"
var textThree: String = "three"

@IBOutlet weak var quoteView: UIView!

var textTimer: Timer!

func toggleText() {
    label.text = isTextOne ? textTwo:textOne
    isTextOne = !isTextOne
    fadeViewInThenOut(view: quoteView, delay: 2)
}

func fadeViewInThenOut(view : UIView, delay: TimeInterval) {
    let animationDuration = 0.25

    // Fade in the view
    UIView.animate(withDuration: animationDuration, animations: { () -> Void in
        view.alpha = 1
    }) { (Bool) -> Void in
        // After the animation completes, fade out the view after a delay

        UIView.animate(withDuration: animationDuration, delay: delay, options: .curveEaseInOut, animations: { () -> Void in
            view.alpha = 0
        }, completion: nil)
    }
}

2 个答案:

答案 0 :(得分:1)

这就是我做到的。

var Quote: String = ""


    var gameTimer: Timer!
    var textTimer: Tr!ime

    func fadeViewInThenOut(view : UIView, delay: TimeInterval) {

            let animationDuration = 0.25

            // Fade in the view
            UIView.animate(withDuration: animationDuration, animations: { () -> Void in
                view.alpha = 1
            }) { (Bool) -> Void in

                // After the animation completes, fade out the view after a delay

                UIView.animate(withDuration: animationDuration, delay: delay, options: .curveEaseInOut, animations: { () -> Void in
                    view.alpha = 0
                },
                            completion: nil)
            }
        }

        func runTimedCode() {

            fadeViewInThenOut(view: quoteView, delay: 0.7)


            func randomNumber(_ arrayLength: Int) -> Int {
                let unsignedArrayCount = UInt32(arrayLength)
                let unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
                let randomNumber = Int(unsignedRandomNumber)


                return randomNumber
            }

            // Importing Quotes plist File
            let quotes = ImportList(FileName: "QuotesList")

            // Selects Quote
            let chosenQuote: String = quotes.array[randomNumber(quotes.count())] as! String

            // Assigns Quote & Author to IBOutlet
            Quote = chosenQuote

            label.text = Quote

        }

我把它放在视图中加载

gameTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)

答案 1 :(得分:0)

你必须实现它

  1. 创建一个单词列表,其中包含需要在文本视图中显示的所有文本/单词
  2. 创建一个方法,该方法返回范围[0-(n-1)之间的随机数,其中n是要显示的单词列表的总大小]
  3. 每隔2秒或固定间隔,调用上述方法为您提供随机数,可用于获取列表中该位置的单词。