2014-12-04 118 views
1

如果我的按钮添加到故事板中,我知道如何创建弹出式菜单,但是如何通过代码创建按钮来创建弹出式菜单。通过长按代码创建按钮的弹出式菜单

UIButtonS *button = [UIButtonS buttonWithType:UIButtonTypeRoundedRect];    
[button addTarget:self action:@selector(siteButtonPressed:)forControlEvents:UIControlEventTouchUpInside]; 
[button setTitle:string1 forState:UIControlStateNormal]; 
button.frame = CGRectMake(XLocatioan, YLocation, 90, 30); 

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] 
                initWithTarget:self 
                action:@selector(handleLongPress:)]; 
longPress.minimumPressDuration = 1.0; 
[button addGestureRecognizer:longPress];  
[self.view addSubview:button]; 

- (void)handleLongPress:(UILongPressGestureRecognizer*)sender { 
    if (sender.state == UIGestureRecognizerStateEnded) { 
    } 
    else if (sender.state == UIGestureRecognizerStateBegan){ 
     //create popover for button 
    } 
} 

回答

1

你已经在做正确的事,但是你正在过度思考。没有必要检查gesture recognizer的状态。如果目标功能已被触发,则意味着用户已经进行了长时间的按压。此外,请注意,并非所有属性state的值都可能受支持。正如文档所述:Some of these states are not applicable to discrete gestures

所以,你的代码应该是这样的(除非你想实现拖动或类似的东西):

UIButtonS *button = [UIButtonS buttonWithType:UIButtonTypeRoundedRect];    
[button addTarget:self action:@selector(siteButtonPressed:)forControlEvents:UIControlEventTouchUpInside]; 
[button setTitle:string1 forState:UIControlStateNormal]; 
button.frame = CGRectMake(XLocatioan, YLocation, 90, 30); 

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] 
                initWithTarget:self 
                action:@selector(handleLongPress:)]; 
longPress.minimumPressDuration = 1.0; 
[button addGestureRecognizer:longPress];  
[self.view addSubview:button]; 

- (void)handleLongPress:(UILongPressGestureRecognizer*)sender { 
    //create popover for button   
} 

如果你的目标是iOS 6+你应该使用一个UIPopoverController创建酥料饼,否则使用UIAlertView