本文介绍了如何使用单次触摸更改UISlider值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发我的第一个iOS应用程序,其中包含 UISlider 。我知道如何在拖动 UISlider 时获取值。但对于我的应用程序,我需要一键式获取滑块的值;即如果我触摸 UISlider 中的某个地方, UILabel 应该显示正确的值。

I'm developing my first iOS app which contains a UISlider. I know how to get the value when the UISlider is dragged. But for my app I need to get the slider's value in a single touch; i.e. if I touch somewhere in the UISlider, a UILabel should display its correct value.

是否可以这样做。任何教程或代码都非常有用。

Is it possible to this way. Any tutorial or code will very helpful.

推荐答案

请写下面代码可能对您有所帮助:))

此处 tapCount int .h文件中声明的变量

- (void)viewDidLoad
{
  tapCount = 0; // Count tap on Slider 

 UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)];
    [slider addGestureRecognizer:gr];

}

 - (void)sliderTapped:(UIGestureRecognizer *)g 
    {
/////////////// For TapCount////////////

        tapCount = tapCount + 1;
        NSLog(@"Tap Count -- %d",tapCount);

/////////////// For TapCount////////////

        UISlider* s = (UISlider*)g.view;
        if (s.highlighted)
            return; // tap on thumb, let slider deal with it
        CGPoint pt = [g locationInView: s];
        CGFloat percentage = pt.x / s.bounds.size.width;
        CGFloat delta = percentage * (s.maximumValue - s.minimumValue);
        CGFloat value = s.minimumValue + delta;
        [s setValue:value animated:YES];

        NSString *str=[NSString stringWithFormat:@"%.f",[self.slider value]];
        self.lbl.text=str;
    }

对于Swift用户

override func viewDidLoad()
{
    super.viewDidLoad()

    tapCount = 0
    let gr = UITapGestureRecognizer(target: self, action: #selector(self.sliderTapped(_:)))
    slider.addGestureRecognizer(gr)

}

func sliderTapped(_ g: UIGestureRecognizer) {

    /////////////// For TapCount////////////
    tapCount = tapCount + 1
    print("Tap Count -- \(tapCount)")
    /////////////// For TapCount////////////

    let s: UISlider? = (g.view as? UISlider)
    if (s?.isHighlighted)! {
        return
    }

    // tap on thumb, let slider deal with it
    let pt: CGPoint = g.location(in: s)
    let percentage = pt.x / (s?.bounds.size.width)!
    let delta = Float(percentage) * Float((s?.maximumValue)! - (s?.minimumValue)!)
    let value = (s?.minimumValue)! + delta
    s?.setValue(Float(value), animated: true)
    let str = String(format: "%.f", slider.value)
    lbl.text = str
}

这篇关于如何使用单次触摸更改UISlider值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 07:49