2

我有 UISlider:

slider = UISlider.alloc.initWithFrame([[20, 70)], [260, 40]])

我希望能够检测到用户何时点击它并知道在哪里。我认为我需要使用UITapGestureRecognizer或类似的东西,但我很陌生,对这一切一无所知。

我可以找出何时点击滑块:

slider.addTarget(self, action:'sliderTaped', forControlEvents:UIControlEventTouchDown)

...但它只适用于拇指,所以这不是很有用,我宁愿抓住滑块上的任何水龙头。

任何指向文档的指针或链接将不胜感激。


相关问题/答案,但使用objective-c:可点击的UISlider

4

1 回答 1

1

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

如果您没有为滑块设置 aminimumValuemaximumValue,则值的范围为0.01.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为单击一下。

于 2012-10-06T20:13:59.063 回答