當滑塊已改爲得到通知,你需要建立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
以單擊自動播放。
我現在看到你想讓滑塊跳到用戶觸摸的點。我會盡力弄清楚並回復你。 – vacawama
感謝您的回答。但是,是的,我想找到如何跳到所觸及的點,而不是得到發生的變化(這是記錄了一下)。 – marcgg
如果你發現那會非常有幫助! – marcgg