iPhone:drawRect 调用一次

标签 iphone objective-c drawrect

我每两秒从 NSTimer 函数调用 setNeedsDisplayInRect 一次。这工作得很好,并在随机位置绘制一个具有随机颜色的正方形。然而,在某些情况下,我想在 NSTimer 函数中绘制一个正方形 x 次(使用 for 循环) - 但是,经过多次错误测试后,即使我正在运行 setNeedsDisplayInRect x 次,drawRect 似乎也只被调用一次次?我希望得到一些帮助,因为我一整天都在试图解决这个问题。卡尔.

编辑下面是我的代码...

查看

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
    CGContextSetFillColorWithColor(context, currentColor.CGColor);
    CGContextAddRect(context, redrawRect);
    CGContextDrawPath(context, kCGPathFillStroke);
}

-(void)drawInitializer 
{
    int x = (int)arc4random() % [self.xCoordinates count]; 
    int y = (int)arc4random() % [self.yCoordinates count]; 
    self.currentColor = [UIColor randomColor];
    self.redrawRect = CGRectMake ([[self.xCoordinates objectAtIndex:x] intValue],       [[self.yCoordinates objectAtIndex:y] intValue], 25, 25);
    [self setNeedsDisplayInRect:redrawRect];
}

Controller

- (void) handleTimer: (NSTimer *) timer
{
    for(int i=0; i<5; i++) 
    {
         [self.squareView drawInitializer];
    }
}

最佳答案

您可以重构代码,以便拥有一个简单的类:

  • 存储颜色
  • 存储位置
  • 有一种方法可以生成随机位置、颜色……

然后,您可以创建任意数量的实例并将它们推送到 NSMutableArray 中。
这样您就可以迭代该列表,并在绘制例程中绘制每个对象。
每当您添加/删除/修改某个对象时,请调用 setNeedsDisplay:

关于iPhone:drawRect 调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2022501/

相关文章:

ios - 后台提取在大约 10 到 14 小时后停止工作

objective-c - Objective-C 中的空对象模式

iOS 推送通知应用程序不要求注册许可

ios - 调用 setNeedsDisplay 时出现快速奇怪的行为

ios - 滚动时如何使UITableView从下往上显示?

iphone - 即使 Wi-Fi 可用,也强制 iPhone 上的 WWAN 连接

iphone - 通过 iPhone 支付商品的选项

ios - 数据未通过 prepareForSegue 查看 Controller

ios - 人脸检测中的人脸边界点检测

java - 如何在矩形中创建矩形?