2015-01-02 2 views
0

"Start"로 설정된 제목 텍스트 속성과 함께 하나의 버튼이있는 매우 기본적인 ios 프로젝트를 만들었습니다. 이 버튼의 수를 15 개로 줄이려고합니다.Xamarin에서 NSTimer로 Button 컨트롤 업데이트하기

다음과 같이 버튼에 대한 이벤트 핸들러를 추가했습니다.

 void StartButton_TouchUpInside (object sender, EventArgs ea) { 

     _currentCount = 15; 

     _timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1),() => 
      { 

       if (_currentCount <= 0) { 
        StartButton.TitleLabel.Text = "Start"; 
        _timer.Dispose(); 
       } else { 
        string titleText = (_currentCount--).ToString(); 
        //Console.WriteLine(titleText); 
        StartButton.TitleLabel.Text = titleText; 
        //Console.WriteLine(StartButton.TitleLabel.Text); 
        //StartButton.SetNeedsDisplay(); 
       } 
      }); 
    } 

여기 이상한 점이 있습니다. 버튼이 15로 바뀌면 "시작", 14로 다시 깜박입니다. 그런 다음 13을 시작한 다음 12 등 ... 등 ...

왜 이렇게할까요? 그리고 어떻게 그것이 시작하는 것을 깜박이는 것을 막을 수 있습니까? 미리 감사드립니다.

+0

타이머 위양 코드 내부 카운트 변수를 넣어보십시오 –

답변

0

봅니다 this.InvokeOnMainThread를 사용하는

private int counter = 0; 
    public override void WillActivate() 
    {   
    Console.WriteLine ("{0} will activate", this); 
    _timer = NSTimer.CreateRepeatingScheduledTimer(1, (timer) => 
    { 
     this.InvokeOnMainThread(()=>{ 
      Console.WriteLine("++++++++ NSTimer Call"); 
      this.AlertTimeLabel.SetText(counter.ToString()); 
      counter++; 
     }); 
    }); 
    } 
관련 문제