Activating Code on Button Press and hold ONLY
I'm trying to activate a section of my code upon press (and hold) o开发者_JAVA技巧f a button only. When the button is released, I want my label to be invisible again. Is there a way to do this effectively? I have an IBAction (the button), and an IBOutlet (A textfield), with this code set for the action:
- (IBAction)toggleIt:(id)sender {
if ([myDescription isHidden]) {
[myDescription setHidden:NO];
} else {
[myDescription setHidden:YES];
}
}
Any help? (In dummies terms)
Zach
I'm afraid there is no way of doing this in IB on the Mac as it would be possible on iOS:
UIKit and AppKit — although similar in many regards — are two very different beasts. Where AppKit has a heritage that reaches back well into to the 1990s (maybe even late 1980s) which shows through in a few spots (I'm looking at you, NSCell), UIKit was designed with the experience of some 20 years on top of AppKit.
And while you can easily tell a UIControl
when its action is going to be invoked (and can have different actions for different events), NSControl
merely allows you to specify one single action to be sent.
If you don't want to override -[NSButtonCell stopTracking:at:inView:mouseIsUp:]
or -[NSButton mouseDown:]
and -[NSButton mouseUp:]
, the easiest way you can achieve what you want should be to set the button to send its action continuously. This can be bone in IB (in the "Attributes" inspector under the "Control" category).
The next thing would be to make your description layer-backed and rewrite your action method in a way like this:
- (IBAction)toggleIt:(id)sender {
CALayer *descriptionLayer = [myDescription layer];
[descriptionLayer setHidden:NO]; // (ab-)use implicit animation
[descriptionlayer performSelector:@selector(setHidden:) withObject:@"" afterDelay:.1];
}
How it works:
The "hidden"-property of CALayer is animate-able and as such, changing it will cause an implicit animation. Since Objective C is just C, anything that is not 0x0
is interpreted as YES
and that is where the third line strikes: The empty string clearly isn't 0x0
so shortly after this action returned, the layer will be called to hide. But since CATransitions happen gradually and can be updated mid-course, this will only affect the visibility of the layer when the action is no longer triggered — i.e. the buton is no longer pressed.
You could use the UIControlEventTouchDown
to hide your label, and then show it on the UIControlEventTouchUpInside
event.
-(IBAction)buttonHit {
[myDescription setHidden:NO];
}
-(IBAction)buttonReleased {
[myDescription setHidden:YES];
}
精彩评论