要在滑块更改时收到通知,您需要设置target/action
. 是包含您要调用的target
方法的对象, 是您要调用action
的方法。我打电话给我的action
sliderValueChanged:
。你可以选择任何东西。一定要在名称后面加上冒号,因为这会告诉它向作为UISlider
对象的发送者发送一个指针。您需要发件人,以便您可以询问滑块的值。
如果您没有为滑块设置 aminimumValue
和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
为单击一下。