Detecting touches on a UISlider?

若如初见. 提交于 2019-11-30 22:50:44

问题


I have a UISlider on screen, and I need to be able to detect when the user stops touching it. (so I can fade some elements away).

I have tried using:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

but this did not work when ending touches on a slider.


回答1:


You can detect when a touch ends using two control events; try

[slider addTarget:self action:@selector(touchEnded:) 
                       forControlEvents:UIControlEventTouchUpInside];

or

[slider addTarget:self action:@selector(touchEnded:) 
                       forControlEvents:UIControlEventTouchUpOutside];

If you want to detect both types of the touchesEnd event, use

[slider addTarget:self action:@selector(touchEnded:) 
   forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];



回答2:


Instead of using touchesEnded: (which shouldn't be used for this purpose anyway), attach an action to the UISlider's UIControlEventValueChanged event and set the continuous property of the UISlider to NO, so the event will fire when the user finishes selecting a value.

mySlider.continuous = NO;
[mySlider addTarget:self
          action:@selector(myMethodThatFadesObjects) 
          forControlEvents:UIControlEventValueChanged];



回答3:


I couldn't get anything to capture both the start and end of the touches, but upon RTFD-ing, I came up with something that will do both.

  @IBAction func sliderAction(_ sender: UISlider, forEvent event: UIEvent) {

    if let touchEvent = event.allTouches?.first {
      switch touchEvent.phase {
      case .began:
        print("touches began")
        sliderTouchBegan()
      case .ended:
        print("touches ended")
        sliderTouchEnded()
      default:
        delegate?.sliderValueUpdated(sender.value)
      }
    }
  }

sliderTouchBegan() and sliderTouchEnded() are just methods I wrote that handle animations when the touch begins and when it ends. If it's not a begin or end, it's a default and the slider value updates.



来源:https://stackoverflow.com/questions/10971154/detecting-touches-on-a-uislider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!