我以编程方式为基于图块的游戏创建UIViews网格。麻烦的是,在三乘三网格中,只有中心区块在初始化时被绘制。其他图块会在他们被点击时显示 - 但直到(这不是非常好) - 并且在其他时间对图块的更改通常不会出现。我已经从Mac OS NSViews调整了我的代码(效果非常好)。
在'网格'的子类中UIView(即' tile' UIViews的容器):
- (void)renewRows:(NSInteger)rows columns:(NSInteger)columns {
for (int i=0; i<rows; i++) {
for (int j=0; j<columns; j++) {
CGRect tileRect;
tileRect.origin.x = j*tileSize.width;
tileRect.origin.y = i*tileSize.height;
tileRect.size.width = tileSize.width;
tileRect.size.height = tileSize.height;
id tileView = [[tilePrototype alloc]initWithFrame:tileRect patternNumber:arc4random_uniform(3) + 1];
//add touch recogniser. Will need additional recognisers for left and right swipe
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tapTile:)];
[tileView addGestureRecognizer:singleFingerTap];
[self addSubview:tileView];
}
}
}
除了瓷砖在点击时正确显示(和动画)的事实之外,我可以通过在调试中单步执行此代码来看到正在创建的图块。
在我的Tile UIView中,我有一个drawRect,如下所示:
- (void)drawRect:(CGRect)dirtyRect {
NSLog(@"%f %f %f %f", dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height);
CGContextRef context = UIGraphicsGetCurrentContext();
_grid = (YANGrid *)[self superview];
double tileWidth = dirtyRect.size.width;
if (_flags.isRotating || _flags.iscentrenode ) {
CGRect centredSquare = CGRectMake(-(tileWidth/4), -(tileWidth/4), tileWidth/2, tileWidth/2);
[_backgroundColor set];
UIRectFill(dirtyRect);
CGContextSaveGState(context);
[self drawPatternConnections];
// Render Nodes
if (_flags.iscentrenode) {
[PatternGraphics centrenodeInRect:¢redSquare];
} else if (_flags.deviceType) {
[PatternGraphics outletnodeInRect:¢redSquare turnedOn:(_flags.isPowered && !_flags.isRotating)];
}
CGContextRestoreGState(context);
}
}
这里的任何人都可以看到我是否遗漏了任何东西 - 为什么我的瓷砖UIViews没有被正确绘制!