我创建了一个Slider(作为视频的控件,就像YouTube在底部一样)并设置最大值(持续时间)和最小值.然后用来SeekToTime
改变currentTime.现在,用户可以滑动滑块的拇指来更改值
我想要实现的是让用户点击滑块上的任意位置并设置视频的当前时间.
我从这个答案中得到了一个方法,我试着将它应用到我的案例中,但是无法使它成功
class ViewController: UIViewController, PlayerDelegate { var slider: UISlider! override func viewDidLoad() { super.viewDidLoad() // Setup the slider } func sliderTapped(gestureRecognizer: UIGestureRecognizer) { // print("A") let pointTapped: CGPoint = gestureRecognizer.locationInView(self.view) let positionOfSlider: CGPoint = slider.frame.origin let widthOfSlider: CGFloat = slider.frame.size.width let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider) slider.setValue(Float(newValue), animated: true) } }
我认为这应该有用,但没有运气.然后我尝试在尝试将"A"打印到日志时进行调试,但事实并非显然不会进入该sliderTapped()
功能.
我究竟做错了什么?或者有更好的方法来实现我想要实现的目标吗?
看起来你需要根据上面的代码示例在viewDidLoad()中实际初始化tap手势识别器.那里有评论,但我没有看到识别器在任何地方被创建.
斯威夫特2:
class ViewController: UIViewController { var slider: UISlider! override func viewDidLoad() { super.viewDidLoad() // Setup the slider // Add a gesture recognizer to the slider let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "sliderTapped:") self.slider.addGestureRecognizer(tapGestureRecognizer) } func sliderTapped(gestureRecognizer: UIGestureRecognizer) { // print("A") let pointTapped: CGPoint = gestureRecognizer.locationInView(self.view) let positionOfSlider: CGPoint = slider.frame.origin let widthOfSlider: CGFloat = slider.frame.size.width let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider) slider.setValue(Float(newValue), animated: true) } }
斯威夫特3:
class ViewController: UIViewController { var slider: UISlider! override func viewDidLoad() { super.viewDidLoad() // Setup the slider // Add a gesture recognizer to the slider let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(gestureRecognizer:))) self.slider.addGestureRecognizer(tapGestureRecognizer) } func sliderTapped(gestureRecognizer: UIGestureRecognizer) { // print("A") let pointTapped: CGPoint = gestureRecognizer.location(in: self.view) let positionOfSlider: CGPoint = slider.frame.origin let widthOfSlider: CGFloat = slider.frame.size.width let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider) slider.setValue(Float(newValue), animated: true) } }
它似乎只是继承UISlider并返回始终为true的beginTracking产生所需的效果.
iOS 10和Swift 3
class CustomSlider: UISlider { override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { return true } }
之后在代码中使用CustomSlider而不是UISlider.