Подтвердить что ты не робот

UIButton с удержанием действия и действием

Я хочу создать UIButton, который можно удерживать, когда он удерживается, он вызывает однократное нажатие. когда он отпущен, вызывает действие "hold is release".

Этот код работает некорректно, так как прикосновение может перемещаться внутри кнопки, и события не запускаются в правильном порядке.

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

события управления обработкой основаны на реализации блока UIBUtton +

4b9b3361

Ответ 1

попробуйте это

  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");

  }

для случая NSPratik: u может использовать событие UIControlEventTouchUpOutside Если пользователь долго нажимает кнопку и через некоторое время вместо отпускания пальца пользователь вытащит свой палец из рамки кнопки. просто добавьте еще одно событие.

  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 frame

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

Быстрая версия

    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(testButton)

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

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

Ответ 2

Попробуйте это

Добавить TouchDown, Touch Up Inside, Прикоснуться к внешнему событию к кнопке ur

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
 }

Ответ 3

Я столкнулся с этой проблемой сам, и в основном мы используем эти события: -

//Это событие отлично работает и срабатывает

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

//Это не срабатывает вообще

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

Решение: -

Использовать длинный указатель жестов нажатия: -

 UILongPressGestureRecognizer *btn_LongPress_gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleBtnLongPressgesture:)];
[aButton addGestureRecognizer:btn_LongPress_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];
}
}

Ответ 4

    **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
 }

Ответ 5

перетащите кнопку из инструментов (панель) и щелкните правой кнопкой мыши по ней. Появится список, найдите "коснуться внутри" и нажмите и перетащите по круговой точке, что перед текстом и переместите его в viewcontroller.h и определите имя и в viewcontroller.m сделать это.

nslog("clicked in"); повторите все действия для касания и найдите соответствующее событие из списка

Ответ 6

Вам нужно подключиться к следующим двум событиям: 1. Нажмите "вниз", "2.Touch Up Inside to it". Методы IBAction. Это будет весело в Interface Builder. Но вы можете сделать это программно и с помощью addTarget: action: forControlEvents: