通过长按代码创建的按钮弹出窗口

时间:2014-12-04 14:57:31

标签: ios xcode twitter-bootstrap uibutton

如果我的按钮添加到故事板,我知道如何创建弹出窗口,但如果我的按钮是通过代码创建的,我怎么能创建popover。

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 个答案:

答案 0 :(得分: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