Как определить количество нажатий

использует session.get (*. class, id); но не загружать функцию

1
задан Abhinav Jha 16 January 2019 в 11:46
поделиться

4 ответа

class ViewController: UIViewController {

  var tapCount: Int = 0

  override func viewDidLoad() {
        super.viewDidLoad()

       tapButton.addTarget(self, action: #selector(multipleTap(sender:)), for: .touchUpInside)

  }

      @objc func multipleTap(sender: UIButton) {
         tapCount += 1
         if tapCount == 3 {
             print(tapCount) //3
         }
    }
}
0
ответ дан Abhishek Jadhav 16 January 2019 в 11:46
поделиться

введем var для хранения счетчиков

ваш измененный код будет:

tapButton.addTarget(self, action: #selector(singleTap(_:)), for: .touchUpInside)


    private var numberOfTaps = 0
    private var lastTapDate: Date?

    @objc private func singleTap(_ sender: UIButton) {
        if let lastTapDate = lastTapDate, Date().timeIntervalSince(lastTapDate) <= 1 { // less then a second
            numberOfTaps += 1
        } else {
            numberOfTaps = 0
        }

        lastTapDate = Date()

        if numberOfTaps == 3 {
          // do your rewind stuff here 30 sec
          numberOfTaps = 0
        }

    }

редактировать: я не читатель, но я думаю, вы ищете что-то похожее выше код)

0
ответ дан Mykola Savula 16 January 2019 в 11:46
поделиться

Вам нужно проверить разницу во времени для сенсорных событий. Например: если кнопка нажата 4 раза и в определенное время, скажем, 1 секунда, если она не нажимается снова, вы можете напечатать 4 нажатия, в противном случае не печатать.

Для этого вам также необходимо вызвать таймер, чтобы вы могли проверить время последнего события и напечатать соответственно.

var timer : Timer?
var timeDuration = 2.0
var tapCount = 0
var lastButtonPressedTime : Date?

@IBAction func tapCountButtonAction(_ sender: UIButton) {
    lastButtonPressedTime = Date()
    if(tapCount == 0){
        tapCount = 1
        timer = Timer.scheduledTimer(withTimeInterval: timeDuration, repeats: true, block: { (timer) in
            let difference = Calendar.current.dateComponents([.second], from:self.lastButtonPressedTime!, to:Date())
            if(difference.second! > 1){
                print(self.tapCount)
                timer.invalidate()
                self.tapCount = 0
            }
        })
    }else{
        tapCount += 1
    }
}
0
ответ дан Mahak Mittal 16 January 2019 в 11:46
поделиться

Методика, используемая здесь, представляет временную задержку при выполнении окончательного действия

static let tapCount = 0

tapButton.addTarget(self, action: #selector(multipleTap(_:event:)), for: UIControl.Event.touchDownRepeat)

// An average user can tap about 7 times in 1 second using 1 finger 
DispatchQueue.main.asyncAfter(deadLine: .now() + 1.0 /* We're waiting for a second till executing the target method to observe the total no of taps */ ) {
    self.performAction(for: tapCount)
}

@objc func multipleTap(_ sender: UIButton, event: UIEvent) {
    tapCount += 1   
}

/// Perform the respective action based on the taps
private func performAction(for count: Int) {

    // Resetting the taps after 1 second
    tapCount = 0

    switch (count){
    case 2:
        // Handle 2 clicks  
    case 3:
        // Handle 3 clicks  
    case 4:
        // Handle 4 clicks
    default:
        print("Action undefined for count: \(count)")
    }
}
0
ответ дан piet.t 16 January 2019 в 11:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: