iPhone开发:iPad的自定义菜单项研究
3.2开始可以自定义菜单项了,根据iPadProgrammingGuide小小的研究了一下,
参考了如下链接http://github.com/billymeltdown/copylabel
基本思路如下
custom一个UIView或UIControl,通过touch使它获取焦点即[self becomeFirstResponder],然后把菜单show出来就可以了
代码
#import <UIKit/UIKit.h>
@interface CustomControl : UIControl {
CGPoint thePoint;
}
- (void)showMenu;
@end
#import "CustomControl.h"
@implementation CustomControl
-(void)changeColor:(id)sender{
NSLog(@"changeColor");
static int rand = -1;
if (++rand==4)
rand=0;
UIColor *color = nil;
switch (rand) {
case 0:
color = [UIColor greenColor];
break;
case 1:
color = [UIColor yellowColor];
break;
case 2:
color = [UIColor magentaColor];
break;
case 3:
color = [UIColor purpleColor];
break;
default:
break;
}
self.backgroundColor = color;
}
-(void)noTouch:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Don't touch me!"
message:nil
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"I Know",nil];
[alert show];
[alert release];
}
- (void)showMenu {
UIMenuController *theMenu = [UIMenuController sharedMenuController];
CGRect theFrame = [[self superview] frame];
CGRect selectionRect = CGRectMake(thePoint.x, theFrame.origin.y - 5.0, 0, 0);
UIMenuItem *menuItem = [[[UIMenuItem alloc] initWithTitle:@"Change Color"
action:@selector(changeColor:)] autorelease];
UIMenuItem *menuItem1 = [[[UIMenuItem alloc] initWithTitle:@"Don't touch me!"
action:@selector(noTouch:)] autorelease];
//theMenu.arrowDirection = UIMenuControllerArrowLeft;
theMenu.menuItems = [NSArray arrayWithObjects:menuItem,menuItem1,nil];
[theMenu setTargetRect:selectionRect inView:self];
[theMenu setMenuVisible:YES animated:YES];
}
- (void)copy:(id)sender {
NSLog(@"copy");
//override
}
- (void)paste:(id)sender{
NSLog(@"paste");
//override
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
BOOL answer = NO;
if (action == @selector(copy:)){
//answer = YES;
}
if (action == @selector(paste:)) {
//answer = YES;
}
if (action == @selector(changeColor:)) {
answer = YES;
}
if (action == @selector(noTouch:)) {
answer = YES;
}
return answer;
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([self canBecomeFirstResponder]) {
[self becomeFirstResponder];
UITouch *touch = [touches anyObject];
thePoint = [touch locationInView:self];
[self performSelector:@selector(showMenu) withObject:nil afterDelay:0.8f];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)dealloc {
[super dealloc];
}
@end