我有UISlider:
slider = UISlider.alloc.initWithFrame([[20, 70)], [260, 40]])
我希望能够检测用户何时点击它并知道在哪里。我认为我需要使用UITapGestureRecognizer
或类似的东西,但我对这一切都是新的和无能为力。
我可以找出滑块被点击的时间:
slider.addTarget(self, action:'sliderTaped', forControlEvents:UIControlEventTouchDown)
...但它只适用于拇指,所以这不是很有用,我宁可抓住任何滑块。
任何指向文档的指针或链接都将受到赞赏。
相关问题/答案,但有目标-c:Clickable UISlider
答案 0 :(得分:1)
要在滑块更改后收到通知,您需要设置target/action
。
target
是包含您想要调用的方法的对象,action
是
你想要的方法。我打电话给我action
sliderValueChanged:
。你可以选择任何东西。确保将冒号附加到名称,因为它告诉它发送指向发件人的指针,即UISlider
对象。您需要发件人,以便您可以询问滑块的值。
如果您没有为滑块设置minimumValue
和maximumValue
,则值的范围将从0.0
到1.0
。
def viewDidLoad
slider = UISlider.alloc.initWithFrame([[20, 70], [260, 40]])
slider.addTarget(self, action:'sliderValueChanged:', forControlEvents:UIControlEventValueChanged)
self.view.addSubview(slider)
end
def sliderValueChanged(sender)
puts sender.value
end
如图所示,当用户移动滑块时,将sliderValueChanged
连续调用。要仅在用户停止触摸滑块时收到通知,请设置:
slider.continuous = no
现在,如果你想要一个可点击的滑块将拇指移动到你点击的位置,那么你需要在滑块上添加UITapGestureRecognizer
。此代码演示了这一点:
def viewDidLoad
slider = UISlider.alloc.initWithFrame([[50, 50], [200, 40]])
tapGestureRecognizer = UITapGestureRecognizer.alloc.initWithTarget(self, action:'sliderTapped:')
tapGestureRecognizer.numberOfTapsRequired = 2
slider.addGestureRecognizer(tapGestureRecognizer)
slider.continuous = false
slider.minimumValue = 77
slider.maximumValue = 129
slider.addTarget(self, action:'sliderValueChanged:', forControlEvents:UIControlEventValueChanged)
self.view.addSubview(slider)
end
# This is called when the slider changes either from taps or from moving the thumb
def handle_new_slider_value(value)
puts "New slider value: #{value}"
end
def sliderValueChanged(slider)
handle_new_slider_value(slider.value)
end
# These were determined empirically by setting the thumb to the minimum and
# then clicking on the center and printing out gestureRecognizer.locationInView(slider).x
# and then repeating for the maximum.
SLIDER_MIN = 11
SLIDER_MAX = 189
def sliderTapped(gestureRecognizer)
if gestureRecognizer.state == UIGestureRecognizerStateEnded
slider = gestureRecognizer.view
x = gestureRecognizer.locationInView(slider).x
# Uncomment this to determine values for SLIDER_MIN/SLIDER_MAX
# puts x
x = SLIDER_MIN if x < SLIDER_MIN
x = SLIDER_MAX if x > SLIDER_MAX
slider_min_val = slider.minimumValue
slider_max_val = slider.maximumValue
# Convert from the location in the view to the slider value
slider.value = slider_min_val + (x - SLIDER_MIN) / (SLIDER_MAX - SLIDER_MIN) * (slider_max_val - slider_min_val)
handle_new_slider_value(slider.value)
end
end
请注意,此代码会在双击时移动滑块。我只需轻轻一按就会遇到麻烦,因为如果您快速移动拇指,代码会将其视为水龙头并将拇指按回到其起始位置。设置tapGestureRecognizer.numberOfTapsRequired = 1
即可轻松点击。