2014-12-04 153 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