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

问题描述:

我有UITextView,我想要做的是在2秒后添加不同的文本。因此,每2秒钟文字将消失,并出现另一个文字。我只用2个文本就完成了这个任务,但是如果我想要更多的话,该怎么办?在一定的时间内从UITextView更改文本

下面的代码会告诉你我是如何做的:

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

你必须实现它

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

这就是我是如何做到的。

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)