ios 带有按住动作和释放动作的 UIButton

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19225475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:09:53  来源:igfitidea点击:

UIButton with hold down action and release action

iosobjective-cuibuttonuitouch

提问by Avner Barr

I want to create a UIButton that can be held down, when held down it calls the "hold down" action once. when it is released, calls the "hold was release" action.

我想创建一个可以按住的 UIButton,按住时它会调用一次“按住”动作。当它被释放时,调用“hold was release”动作。

This code isn't working correctly because the touch can move inside the button and the events aren't triggered in correct order

此代码无法正常工作,因为触摸可以在按钮内移动并且事件未按正确顺序触发

[button handleControlEvent:UIControlEventTouchDown withBlock:^{
        [self performMomentaryAction:PXActionTypeTouchDown];
    }];
[button handleControlEvent:UIControlEventTouchUpInside withBlock:^{
        [self performMomentaryAction:PXActionTypeTouchUp];
    }];

handle control events is based on UIBUtton+block implementation

处理控件事件基于UIBUtton+block实现

回答by Shankar BS

try this

尝试这个

  UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  aButton.frame = CGRectMake(xValue, yValue, 45, 45);
  [aButton addTarget:self action:@selector(holdDown) forControlEvents:UIControlEventTouchDown];
  [aButton addTarget:self action:@selector(holdRelease) forControlEvents:UIControlEventTouchUpInside];


 - (void)holdDown
  {
     NSLog(@"hold Down");
  }

  - (void)holdRelease
  {
      NSLog(@"hold release");

  }

for NSPratik's case: u can use the event UIControlEventTouchUpOutsideIf user long press button and after some time, instead of releasing the finger, user will move his/her finger out of the bounds of button. just add one more event.

对于 NSPratik 的情况:你可以使用事件UIControlEventTouchUpOutsideIf user long press button 和一段时间后,用户将他/她的手指移出按钮的边界而不是释放手指。只需再添加一个事件。

  UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  aButton.frame = CGRectMake(xValue, yValue, 45, 45);
  [aButton addTarget:self action:@selector(holdDown) forControlEvents:UIControlEventTouchDown];
  [aButton addTarget:self action:@selector(holdRelease) forControlEvents:UIControlEventTouchUpInside];
  [aButton addTarget:self action:@selector(holdReleaseOutSide) forControlEvents:UIControlEventTouchUpOutside]; //add this for your case releasing the finger out side of the button's frame

 //add this method along with other methods 
  - (void)holdReleaseOutSide
  {
     NSLog(@"hold release out side");
  }

Swift Version

迅捷版

 var  aButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
 aButton.frame = CGRectMake(xValue,yValue, 45, 45)
 aButton.setTitle("aButton", forState: UIControlState.Normal)
 aButton.backgroundColor = UIColor.greenColor()
 aButton.addTarget(self, action: Selector("holdRelease:"), forControlEvents: UIControlEvents.TouchUpInside);
 aButton.addTarget(self, action: Selector("HoldDown:"), forControlEvents: UIControlEvents.TouchDown)
 self.addSubview(aButton)

 //target functions   
 func HoldDown(sender:UIButton)
 {
    print("hold down")
 }

 func holdRelease(sender:UIButton)
 {
    print("hold release")
 }

回答by Ashish

I have faced this problem myself, and mostly we use these events:-

我自己也遇到过这个问题,大多数情况下我们使用这些事件:-

// This event works fine and fires

// 此事件工作正常并触发

[aButton addTarget:self action:@selector(holdDown) forControlEvents:UIControlEventTouchDown];

// This does not fire at all

// 这根本不会触发

[aButton addTarget:self action:@selector(holdRelease) forControlEvents:UIControlEventTouchUpInside];

Solution:-

解决方案:-

Use Long Press Gesture Recognizer:-

使用长按手势识别器:-

 UILongPressGestureRecognizer *btn_LongPress_gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleBtnLongPressgesture:)];
[aButton addGestureRecognizer:btn_LongPress_gesture];

Implementation of gesture:-

手势的实现:-

- (void)handleBtnLongPressgesture:(UILongPressGestureRecognizer *)recognizer{


//as you hold the button this would fire

if (recognizer.state == UIGestureRecognizerStateBegan) {

    [self holdDown];
}

//as you release the button this would fire

if (recognizer.state == UIGestureRecognizerStateEnded) {

    [self holdRelease];
}
}

回答by Kalpesh

Try this

尝试这个

Add TouchDown ,Touch Up Inside, Touch Up Outside event to ur button

将 TouchDown 、Touch Up Inside、Touch Up 外部事件添加到您的按钮

enter image description here

在此处输入图片说明

 -(IBAction)theTouchDown:(id)sender
 {

    timer = [NSTimer scheduledTimerWithTimeInterval:0.2
                                             target:self
                                           selector:@selector(performFunctionality)
                                           userInfo:nil
  }
-(IBAction)theTouchUpInside:(id)sender
{
[timer invalidate];
timer = nil;
[self performFunctionality];

 }


 -(IBAction)theTouchUpOutside:(id)sender
 {
[timer invalidate];
timer = nil;
 }

-(void)performFunctionality
 {
 //write your logic
 }

回答by Jaydip

    **in Swift 3.0,**

btnPasswordShow.addTarget(self, action:#selector(btnShowPasswordClickHoldDown), for: .touchDown)

btnPasswordShow.addTarget(self, action:#selector(btnShowPasswordClickRelease), for: .touchUpInside)

 func btnShowPasswordClickHoldDown(){
    txtpassword.isSecureTextEntry = false
 }

 func btnShowPasswordClickRelease(){
     txtpassword.isSecureTextEntry = true
 }

回答by sadegh bitarafan

You can use Timer and and button touchup to handle this action

您可以使用计时器和按钮修饰来处理此操作


 var timer: Timer?

    @IBAction func dowm(_ sender: UIButton) {
        timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true, block: { (time) in
            print("im hold in ")
        })
    }

    @IBAction func up(_ sender: UIButton) {
        timer!.invalidate()

    }

this two @IBAction are for handle touch up and touch down button when button touch down timer is started and print something and when button is going u invalidate timer.

这两个@IBAction 用于在按钮触摸计时器启动并打印某些内容时以及按钮运行时使计时器无效时的手柄触摸向上和向下按钮。

access to completed project from Github :

从 Github 访问已完成的项目:

https://github.com/sadeghgoo/RunCodeWhenUIbuttonIsHeld

https://github.com/sadeghgoo/RunCodeWhenUIbuttonIsHeld

回答by User99

drag a button from tools(pane) and right click on it.a list will occur find "touch up inside" and click and drag on circle point that on front of text and move it to viewcontroller.h and define a name and in viewcontroller.m do this.

从工具(窗格)中拖动一个按钮并右键单击它。将出现一个列表,找到“内部修饰”,然后单击并拖动文本前面的圆点并将其移动到 viewcontroller.h 并在 viewcontroller 中定义名称.m 这样做。

nslog("clicked in");repeat all action for touch out and find an appropriate event from list

nslog("clicked in");重复所有触摸操作并从列表中找到合适的事件

回答by Amulya

You need to connect following two events 1.Touch Down ,2.Touch Up Inside to it's IBAction Methods .It will be fun in Interface Builder. But you can do it programmatically also using addTarget: action: forControlEvents:

您需要将以下两个事件 1.Touch Down ,2.Touch Up 连接到它的 IBAction Methods 里面。在 Interface Builder 中会很有趣。但是您也可以使用 addTarget: action: forControlEvents 以编程方式执行此操作: