我为我的应用程序 Compounds 实现了一个元素周期表键盘。
不要使用 UIButtons。
要显示您的键盘,请使用: UIViews 或 CALayers 来显示各个键
或者
静态PNG。记忆和“拉链”要容易得多。(这是我为尚未到来的更新所做的)
您必须使用父视图跟踪所有触摸。(在底部添加小边来解释为什么会这样)像这样实现 touches 方法:
- (void)touchesBegan: (NSSet *)touches
withEvent: (UIEvent *)event {
NSLog(@"TouchDown");
CGPoint currentLocation = [[touches anyObject] locationInView:self.view];
[self magnifyKey:[self keyAtPoint:currentLocation]];
}
-(void)touchesMoved: (NSSet *)touches
withEvent: (UIEvent *)event {
NSLog(@"TouchMoved");
CGPoint currentLocation = [[touches anyObject] locationInView:self.view];
[self magnifyKey:[self keyAtPoint:currentLocation]];
}
-(void) touchesEnded: (NSSet *)touches
withEvent: (UIEvent *)event{
NSLog(@"TouchUp");
CGPoint currentLocation = [[touches anyObject] locationInView:self.view];
int key = [self keyAtPoint:currentLocation];
[self selectKey:aKey];
}
这些方法获取密钥并适当地“放大”选定的密钥。
我针对 CGRects 数组运行该点以确定按键(与命中测试相比,这更快)。
- (int)keyAtPoint:(CGPoint)aPoint{
int aKey=1;
for(NSString *aRect in keys){
if(CGRectContainsPoint(CGRectFromString(aRect), aPoint)){
break;
}
aKey++;
}
if(aKey==kKeyOutOfBounds)
aKey=0;
NSLog([NSString stringWithFormat:@"%i",aKey]);
return aKey;
}
- (void)magnifyKey:(int)aKey{
if(aKey!=0) {
if(magnifiedKey==nil){
self.magnifiedKey = [[[MagnifiedKeyController alloc] initWithKey:aKey] autorelease];
[self.view addSubview:magnifiedKey.view];
}else{
[magnifiedKey setKey:aKey];
if([magnifiedKey.view superview]==nil)
[self.view addSubview: magnifiedKey.view];
}
}else{
if(magnifiedKey!=nil)
[magnifiedKey.view removeFromSuperview];
}
}
- (void)selectKey:(int)aKey{
if(magnifiedKey!=nil){
if(aKey!=0){
[magnifiedKey flash];
[self addCharacterWithKey:aKey];
}
[magnifiedKey.view performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.5];
}
}
那里有一些方法供您实现,但它非常简单。您基本上是在创建一个放大键的视图。然后在用户滑动手指时移动它。
在旁边:
您无法使用子视图跟踪触摸,因为一旦视图跟踪触摸,它就会继续跟踪触摸,直到调用 touchesEnded:(或 touchesCancelled:)。这意味着一旦字母“Q”跟踪触摸,其他键将永远无法访问该触摸。即使您将鼠标悬停在字母“W”上。这是一种你可以在其他地方利用的行为,但在这种情况下,你必须通过一个“父视图”来解决它,它的工作是跟踪触摸。
(更新以修复内存泄漏)