Swift 检测 UISlider 图片点击
Swift Detect UISlider image tap
所以我有一个 UISlider
看起来像这样:
Image here
是这样设置的,所以图片不是UIImageView
的,而是UISlider
里的图片:
Image 2 here
我想添加一个功能,当用户按下左侧的图像时,它运行一个功能,当用户按下右侧的图像时,它运行另一个功能。这可能吗?
以下是您的操作方法。请仔细阅读评论。
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")
}
}
}
所以我有一个 UISlider
看起来像这样:
Image here
是这样设置的,所以图片不是UIImageView
的,而是UISlider
里的图片:
Image 2 here
我想添加一个功能,当用户按下左侧的图像时,它运行一个功能,当用户按下右侧的图像时,它运行另一个功能。这可能吗?
以下是您的操作方法。请仔细阅读评论。
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")
}
}
}