@IBAction から発火する、function() の 連結Swift編 Timer event 時計の作成


Button action による function 任意の文字列(){}からイベントの発生

まずボタンをアクション接続します。接続は、ストーリーボード上で、右上の+ボタンを、オブジェクト選択中に叩きます。※Swiftシートを選択中は、オブジェクトツールは出ません。式の補完候補が出るだけです。


import UIKit
class ViewController: UIViewController {
   var label1 = UILabel()
   var label2 = UILabel()
   var timer = Timer()
   @IBAction weak button1: UIButton{
       label1.text = New Label
       label1.frame = CGRect(x: 40, y: 280, width: self.view.frame.size.width, height: 31)
       label.textColor = .gray
       label.backgroundColor = .black
       self.view.addSubView(label1)
       label2.isHidden = true
       Timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timeUpDate(timer:)) userInfo: nil, repeat: true)
       /* 
         この後がファンクション
      */
      buttonAction()
    }
    //ここに飛ぶ
    func buttonAction(){
        label2.text = Move Label
        label2.textColor = .brown
        let timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(interval(setTimeout:)), userInfo: nil, repeat: false)
        label2.backgroundColor = .blue
    }
    @objc func intervalz(setTimeout: Timer){
        timer2 = Timer2.scheduledTimer(timerInterval: 0.1, target: self, selector: #selector(timeUpDate:)), userInfo: nil, repeat: true)
    }
    @objc func timeUpDate(timer: Timer){
        let nowTime = DateFormatter()
        let nows = DateFormatter()
        let now = Date()
        nowTime.dateFormat = hh:mm:ss
        nows.dateFormat = yyyy/MM/dd
        label1.text = nows.stringFromDate(now)
        label2.text = nowTime.stringFromDate(now)
    }
    override viewDidLoad(){

    }
}

この式の中の、timer の後の Selector任意の文字列が
@objc 任意の文字列{
に繋がっていて、タイムインターバルの5、0.1秒ごとに発生するイベント接続するファンクションをセットし、リピートがあっるものは、インターバル、ないものはタイムアウトイベントとすると定義している。