【问题标题】:drawing views after time intervals时间间隔后的绘图视图
【发布时间】:2015-06-23 08:33:31
【问题描述】:

我需要在时间间隔之后绘制视图,例如创建第一个视图然后等待 5 秒并创建另一个,我正在使用这个:

    -(void) drawView
{
    int x=0;
        x+=16;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, 580, 16, 25)];
        view.backgroundColor = [UIColor blackColor];
        [self.view addSubview:view];

}

[self performSelector:@selector(drawView) withObject:nil afterDelay:4];

【问题讨论】:

  • 看看 NSTimer。我相信这正是您所需要的。它可以是一次性的,也可以是重复的。如果我理解你的话,最后一种模式就是你所需要的
  • 我正在使用 performSelector 方法是 NSTimer 更好的解决方案吗?
  • @AbdelrahmanManna 不是真的,我发现 NSTimer 有时很棘手/错误。看看this question看看有什么区别
  • 嗯,看不出你的方法有什么问题,除非你无法阻止它。 sp,这个方法一旦开始运行,就会一直运行到关闭应用程序
  • @SergiiMartynenkoJr 他的代码只会调用一次drawView

标签: ios objective-c


【解决方案1】:

创建这个方法:

-(void) drawViewsEvery5Seconds
{
    if(!lastView)//should be a member variable
    {
        lastView = [[UIView alloc] initWithFrame:CGRectMake(0, 580, 16, 25)];
    }
    else
    {             
         lastView = [[UIView alloc] initWithFrame:CGRectMake(lastView.frame.origin.x+16, 580, 16, 25)];
    }
    lastView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:lastView];
    [self performSelector:@selector(drawViewsEvery5Seconds) withObject:nil afterDelay:5];
}

然后拨打[self drawViewsEvery5Seconds];

更新

要停止绘制视图,请调用[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(drawViewsEvery5Seconds) object:nil];

【讨论】:

  • 你的意思是我必须这样做? -(void) drawView { int x=16; UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, 580, 16, 25)]; view.backgroundColor = [UIColor blackColor]; [self.view addSubview:view]; } -(void) drawViewsEvery5Seconds { int x = 0; x+=16; UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, 580, 16, 25)]; view.backgroundColor = [UIColor blackColor]; [self.view addSubview:view] [self performSelector:@selector(drawView) withObject:nil afterDelay:5]; }
  • 不,只需使用drawViewsEvery5Seconds。我已经更正了,我在选择器上忘记了 drawView。也让代码更清晰了一点
  • (我想你想每隔 5 秒在右边创建一个新视图)
  • 那么什么是“lastview”?
  • 这是最后创建的视图,你只需要在你的.h中设置UIView *lastView;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 2011-01-13
  • 2014-10-21
  • 2017-03-30
  • 2017-09-24
  • 1970-01-01
相关资源
最近更新 更多