iPhone : How to detect the end of slider drag?

后端 未结 16 2623
不思量自难忘°
不思量自难忘° 2020-12-02 07:36

How to detect the event when the user has ended the drag of a slider pointer?

16条回答
  •  执笔经年
    2020-12-02 08:36

    You can add an action that takes two parameters, sender and an event, for UIControlEventValueChanged:

    [slider addTarget:self action:@selector(onSliderValChanged:forEvent:) forControlEvents:UIControlEventValueChanged]
    

    Then check the phase of the touch object in your handler:

    - (void)onSliderValChanged:(UISlider*)slider forEvent:(UIEvent*)event {     
        UITouch *touchEvent = [[event allTouches] anyObject];
        switch (touchEvent.phase) {     
            case UITouchPhaseBegan:
                // handle drag began
                break;
            case UITouchPhaseMoved:
                // handle drag moved
                break;
            case UITouchPhaseEnded:
                // handle drag ended
                break;
            default:
                break;
        }
    }
    

    Swift 4 & 5

    slider.addTarget(self, action: #selector(onSliderValChanged(slider:event:)), for: .valueChanged)
    
    @objc func onSliderValChanged(slider: UISlider, event: UIEvent) {
        if let touchEvent = event.allTouches?.first {
            switch touchEvent.phase {
            case .began:
                // handle drag began
            case .moved:
                // handle drag moved
            case .ended:
                // handle drag ended
            default:
                break
            }
        }
    }
    

    Note in Interface Builder when adding an action you also have the option to add both sender and event parameters to the action.

提交回复
热议问题