There's a special situation in my app where I need a UIButton touch to be accompanied by a click sound, similar to the one used on the system keyboard.
I'm doing this now on the toucesBegan: call - the earliest one I could think of - but still, in quite a few cases (especially on slower devices), the sound is delayed and the whole point is missed - the user might have touched another button before the first sound is heard.
This does not happen on the system keyboard, nor does it happen in some other apps that I'm using, so they must be doing it the right way :-)
Where should I put the click code to make it sound as soon as the user touches the screen? I'd rather do it in a place where I don't have to check myself whether the touch is within the bounds of the button, but if this is the only choice then I'm willing to do it.
Does the method used for creating the sound matter? I'm now usin开发者_如何学Gog AudioServicesPlaySystemSound which is the easiest way.
Thanks.
As DarkDust said, why you don't use addTarget:action:forControlEvents:
?
For me works fine:
[button addTarget:self action:@selector(playClick) forControlEvents:UIControlEventTouchUpInside];
-(IBAction)playClick{
NSString *effect;
NSString *type;
effect = @"Tink";
type = @"aiff";
SystemSoundID soundID;
NSString *path = [[NSBundle mainBundle] pathForResource:effect ofType:type];
NSURL *url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID ((CFURLRef)url, &soundID);
AudioServicesPlaySystemSound(soundID);
}
The touchesBegan:withEvent:
calls might get delayed if you have a UIGestureRecognizer attached. So you must make sure there's no gesture recognizer on the view.
You could also use addTarget:action:forControlEvents: with event UIControlEventTouchDown
.
精彩评论