Ron*_*iew 5 iphone cocoa-touch objective-c
我有一个自定义UIView,它生成一组子视图,并以像tile这样的行和列显示它们.我想要实现的是允许用户触摸屏幕,当手指移动时,其下方的瓷砖消失.
下面的代码是包含切片的自定义UIView:
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
int i, j;
int maxCol = floor(self.frame.size.width/TILE_SPACING);
int maxRow = floor(self.frame.size.height/TILE_SPACING);
CGRect frame = CGRectMake(0, 0, TILE_WIDTH, TILE_HEIGHT);
UIView *tile;
for (i = 0; i<maxCol; i++) {
for (j = 0; j < maxRow; j++) {
frame.origin.x = i * (TILE_SPACING) + TILE_PADDING;
frame.origin.y = j * (TILE_SPACING) + TILE_PADDING;
tile = [[UIView alloc] initWithFrame:frame];
[self addSubview:tile];
[tile release];
}
}
}
return self;
}
- (void)touchesBegan: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
- (void)touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
Run Code Online (Sandbox Code Playgroud)
这种方法可行,但是如果瓷砖变得更密集(即屏幕上的小瓷砖和更多瓷砖).随着手指的移动,iPhone的响应速度也会降低.可能是hitTest对处理器造成了影响,因为它很难跟上,但想要一些意见.
我的问题是:
这是实现touchesMoved的有效方式/正确方法吗?
如果不是,推荐的方法是什么?
我尝试将功能移动到自定义Tile类(子UIView)中,上面的类将创建并添加为子视图.此子视图Tile可以处理TouchesBegan但是当手指移动时,其他图块也不会接收TouchesBegan,即使触摸仍然是初始触摸序列的一部分.有没有办法通过子视图Tile类实现它,当手指移动时,其他tile如何接收TouchesBegan/TouchesMoved事件?
Ben*_*ieb 11
//In your init method, make sure each tile doesn't respond to clicks on its own
...
tile.userInteractionEnabled = NO;
...
- (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
CGPoint tappedPt = [[touches anyObject] locationInView: self];
int xPos = tappedPt.x / (TILE_SPACING + TILE_PADDING);
int yPos = tappedPt.y / (TILE_SPACING + TILE_PADDING);
int tilesAcross = (self.bounds.size.width / (TILE_SPACING + TILE_PADDING));
int index = xPos + yPos * tilesAcross;
if (index < self.subviews.count) {
UIView *tappedTile = [self.subviews objectAtIndex: index];
tappedTile.hidden = YES;
}
}
Run Code Online (Sandbox Code Playgroud)
(不知道为什么编号在这里重新开始1 ...)
另外,您可以检查点是否位于代表每个子视图框架的CGRect中,而不是命中测试.我有一个类似的应用程序,这对我来说效果最好.
for (UIView* aSubview in self.subviews) {
if([aSubview pointInside: [self convertPoint:touchPoint toView:aSubview] withEvent:event]){
//Do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22913 次 |
| 最近记录: |