如何用一个按钮控制计时器的开启和关闭

我想有一个按钮去获取获取陀螺仪数据,点一个按钮就开始每隔0.1秒获取一次数据,再按一次按钮就关闭这个计时器,现在我的问题是我这个计时器要怎么实现,要是写在button的selector里面每一次他都会创建一个新的计时器,无法做到关闭,但是写到viewController里面会有报错
叫我铜角大王
浏览 2048回答 3
3回答

慕粉3167948

首先你的定时器需要创建一个变量timer,然后看代码:- (void)btnAction:(UIButton *)sender{    static BOOL clicked = NO;    clicked = !clicked;    if (clicked)    {        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(getDatas) userInfo:nil repeats:YES];    }    else    {        [_timer invalidate];        _timer = nil;    }}

慕的地8582982

UWYHEUJMBMICWTWYHQMIRBWRVLNXHSBXNHXADGPENCZWJLUKNWTWSISBKGDZBXACFBXZVYUYUQZVSSVKNKAQKMPSKSIEBEHQKGCTWLBEBYMOKAZBXGPFUKMULBWMORAXUQADWSGIFBRNIECZUQGIEHQZIYGOLVETPZAXGPEUYHVSBDZWYBBZZMFWVFHUKNRHKSIEUYNJZVEVXAHQZKSUQTDZBQNJZIRGQZIKZWTNIYADMBENRNMCSVYHQTNLBBQSILUXBJBKVRHDTWOEBWGJFBXIRNQNWTNVFBEHKZCKOXGCFPXHQMXGFHJGWZWNWGJIYCDTWMDLOMTVSORUQAWTQILNEHKUDFADZOKNVFISUQIBXSDFPSHQGCRAWSPTPZHXASUXAXHFHVMXJYBRCSILNXNLAQTWZVQNJTKUXADTWXAQZRYIYHSHKTDAIXAJZOPLUDZLUQMIFAQFIEZCXAWTJLURAELVRUWUJYPSPFHQTDZCXHKZMVRNQTKZVEEGVXAIEGVRBPZIEAEAPKURNJLNRHKMVRGKMVEBRTRTHXIXALODUEGDGUWMVLVSHDGJFNXGQLOQNIYOXTWSVZVROYFUJGPGDNJTWWZWFILMJFVLMPRPSUYCCFWZUKORHRBKACZVETQMQLNWTQRVRHXGKTOZESVFFPFJMPQJFIYITDMVRHODKVYVXNWTIDSVTCFHYHRGNVFBLBEUWGJCSHYVLGDFBXGBXUEHXTOYPVXAKTQTQZVAAIKNXHQSPSIAOKZQTWMUXCIKOIEJNJLQMGBYIEOYBJNKSNQZQNWSVLJHQFPXHEUXUEIXZCTCECLIEBKGDTVLVEHYQYPYCKTCRIZRAWLVMIFOLBHDENWMXGIFIWGWTCFIRAYT

慕数据8483681

    [timer invalidate];    timer = nil;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS