-
[Swift5] UISlider tap to change value: Tap on UISlider to Set the Value앱 개발자 2023. 8. 22. 23:47반응형
you want to know how to change Uislider value on tapping at particular point on the Uislider.
To change the UISlider value when tapping on a particular point, you can add a tap gesture recognizer to the UISlider and then calculate the value based on the tapped position. Here's how you can achieve this:
Add a Tap Gesture Recognizer:
First, add a tap gesture recognizer to your UISlider.
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(gestureRecognizer:))) slider.addGestureRecognizer(tapGestureRecognizer)
Handle the Tap:
Next, implement the method to handle the tap gesture. In this method, you'll calculate the value based on the tapped position and set it to the slider.
@objc func sliderTapped(gestureRecognizer: UIGestureRecognizer) { let pointTapped: CGPoint = gestureRecognizer.location(in: self.view) let positionOfSlider: CGPoint = slider.frame.origin let widthOfSlider: CGFloat = slider.frame.size.width let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider) slider.setValue(Float(newValue), animated: true) }
Complete Example:
Here's a complete example combining the above steps:
import UIKit class ViewController: UIViewController { @IBOutlet weak var slider: UISlider! override func viewDidLoad() { super.viewDidLoad() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(gestureRecognizer:))) slider.addGestureRecognizer(tapGestureRecognizer) } @objc func sliderTapped(gestureRecognizer: UIGestureRecognizer) { let pointTapped: CGPoint = gestureRecognizer.location(in: self.view) let positionOfSlider: CGPoint = slider.frame.origin let widthOfSlider: CGFloat = slider.frame.size.width let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider) slider.setValue(Float(newValue), animated: true) } }
It is Swift 5 code
Yes, the code provided is compatible with Swift 5. In Swift 5, the syntax, the way gesture recognizers are added, and the way frames and points are accessed remain the same as in the example provided.
With this setup, whenever you tap on the UISlider, it will adjust its value to the tapped position.
However, always ensure that you have set up the necessary connections (e.g., the @IBOutlet for the slider) in your Interface Builder if you're using a storyboard or XIB. If you're setting up your UI programmatically, make sure to initialize the UISlider and add it to the view hierarchy before adding the gesture recognizer.
Happy Coding!
반응형'앱 개발자' 카테고리의 다른 글
Quick Recap: Simplify Your YouTube Viewing with Instant Summaries (5) 2024.09.10 iOS 앱 출시 스크린샷 준비, 피그마&캔바 활용 (0) 2024.06.03 [Swift]여러 서버와 통신하기, URLSession 네트워킹 코드, 제네릭 함수로 만들어 재사용하기 (0) 2023.09.11 Swift JSON 디코딩하는데 타입이 여러 데이터 타입으로 들어온다면? (0) 2023.09.05 IOS 앱 <NEW ME> 기획부터 출시까지 (0) 2022.07.22