Reputation: 47
I created a Gauge using AppCode. Depending on the input, the gauge arrow in the middle rotates. I want to use a slider in Swift to determine how much the arrow in the gauge should rotate. If I hard code the input the arrow rotates to the proper position. For example, if I input 0.5, then the arrow points to the centre of the gauge.
My problem is that my UIView never updates the arrow depending on the new slider position. The arrow is always positioned depending on the UISlider's 'Current' value. How can I get my UIView to update in real time with respect to my UISlider.
I have a feeling that I’m supposed to put my 'drawRect' function in the 'ratingSliderChanged' action function. When I try to do this, my gauge never appears.
import Foundation
import UIKit
class RatingViewController: UIView {
var sliderValue: CGFloat = 0.0
@IBOutlet var newView:UIView!
@IBAction func ratingSliderChanged(sender: UISlider){
sliderValue = CGFloat(sender.value)
println(sliderValue)
}
override func drawRect(rect: CGRect) {
RatingGaugeStyleKit.drawCanvas1(frame: self.bounds, arrowAngle: sliderValue)
}
}
Any Suggestions?
Upvotes: 1
Views: 659
Reputation: 692
Swift 4.2
@IBOutlet weak var sliderObj: UISlider!
@IBOutlet weak var selectionUIView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
sliderFunc()
}
@IBAction func sliderButtonTapped(_ sender: UISlider) {
sliderFunc()
}
func sliderFunc() {
let intObj: Int = Int(sliderObj!.value)
sliderObj.value = roundf(sliderObj.value)
let trackRect = sliderObj.trackRect(forBounds: sliderObj.frame)
let thumbRect = sliderObj.thumbRect(forBounds: sliderObj.bounds, trackRect: trackRect, value: sliderObj.value)
if intObj == 1 {
UIView.animate(withDuration: 0.3, animations: {
self.selectionUIView.center = CGPoint(x: thumbRect.midX, y: self.selectionUIView.center.y)
}) { (isCompleted) in
self.textView.text = "Sachin Tendulkar is scored 50 runs below"
}
} else if intObj == 2 {
UIView.animate(withDuration: 0.3, animations: {
self.selectionUIView.center = CGPoint(x: thumbRect.midX, y: self.selectionUIView.center.y)
}) { (isCompleted) in
self.textView.text = "Sachin Tendulkar is scored 100 runs"
}
}
}
Upvotes: 1
Reputation: 47
So I managed to do it with the help of someone at AppCode.
Basically because the image is dynamic, I need to call
func setNeedsDisplay()
when the UISlider changes. This way, it makes sure to update my UIView when a parameter in my drawing changes. In this case, my parameter is the value from the UISlider.
Hope my explanation is clear for anyone needing this in the future.
Upvotes: 1