【问题标题】:Swift Detect UISlider image tapSwift 检测 UISlider 图像点击
【发布时间】:2021-07-06 09:13:47
【问题描述】:

所以我有一个看起来像这样的UISliderImage here

是这样设置的,所以图片不是UIImageView的,而是UISlider里面的图片: Image 2 here

我想添加一个功能,当用户按下左侧的图像时,它运行一个功能,当用户按下右侧的图像时,它运行另一个功能。这甚至可能吗?

【问题讨论】:

标签: ios swift xcode uislider


【解决方案1】:

您可以这样做。请仔细阅读cmets。

import UIKit

class ViewController: UIViewController {

    // This is linked to your storyboard layout
    @IBOutlet weak var slider: UISlider!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Add a tap gesture recognizer to the slider
        slider.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(sliderTapped(_:))))
    }

    @objc private func sliderTapped(_ tapRecognizer: UITapGestureRecognizer) {
        let location = tapRecognizer.location(in: slider)
        
        // UISlider can tell you min/max value image frames
        // CAUTION: Use images those are big enough to be easy tap targets
        // In my case, I used images of size 30x30
        let minImageRect = slider.minimumValueImageRect(forBounds: slider.bounds)
        let maxImageRect = slider.maximumValueImageRect(forBounds: slider.bounds)
        
        // Now you can check which image out of min/max was tapped
        if minImageRect.contains(location) {
            print("Min Image Tapped")
        } else if maxImageRect.contains(location) {
            print("Max Image Tapped")
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-17
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多