2017-04-27 7 views
-6

私は3つのView Controller(VC)を持っています。私の2番目のVCにはスタートボタンと3番目のVCがあります。私は3番目のVCに移動すると時間が実行されるはずです。これを行う方法? クイズアプリの場合前のView Controllerを参照するには?

+0

このhttp://stackoverflow.com/questions/27894834/swift-how参照-to-use-nstimer-background –

答えて

1

あなたは簡単にこれを行うことができます:

使用してストーリーボードUIを作成します。

enter image description here

コードは以下の通りです:

ViewController2.m:

#import "ViewController2.h" 

@interface ViewController2() 
{ 
    NSTimer *timer; 
    int time_count; 
} 
@property (weak, nonatomic) IBOutlet UILabel *time_label; 

@end 

@implementation ViewController2 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 


    timer = [NSTimer scheduledTimerWithTimeInterval:1 
              target:self 
              selector:@selector(handleTimer:) 
              userInfo:nil 
              repeats:YES]; 

} 
/* 
#pragma mark - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 
*/ 

- (void)handleTimer:(id)sender { 

    _time_label.text = [NSString stringWithFormat:@"%d", time_count++]; 

} 

@end 

結果次のようなものです:

enter image description here


スウィフト3

メインコード:

import UIKit 

class ViewController2: UIViewController { 

    @IBOutlet weak var time_label: UILabel! 

    var time_count = 0 

    override func viewDidLoad() { 
     super.viewDidLoad() 


     Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerHandler), userInfo: nil, repeats: true) 

    } 

    func timerHandler() { 

     self.time_count += 1 
     self.time_label.text = "\(self.time_count)" 
    } 

} 
+0

示されたyuはobj-cにあります。swif t 3 – Thara

+0

@Thara言語はちょうどツールです – aircraft

+0

申し訳ありません私はswift3とobj-cの初心者です – Thara

関連する問題