I'm going through this tutorial about how to make double sliders while also learning how to translate from ObjC to Swift (I only know Swift really but I'm learning a little about ObjC), it's going pretty well but I'm stuck at this one point trying to translate this part to swift. I don't know what a BOUND Macro is for one thing, it's not in any guides like this one, for another I don't know how to translate it to Swift.
Here's the code in objective C:
#define BOUND(VALUE, UPPER, LOWER) MIN(MAX(VALUE, LOWER), UPPER)
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchPoint = [touch locationInView:self];
// 1. determine by how much the user has dragged
float delta = touchPoint.x - _previousTouchPoint.x;
float valueDelta = (_maximumValue - _minimumValue) * delta / _useableTrackLength;
_previousTouchPoint = touchPoint;
// 2. update the values
if (_lowerKnobLayer.highlighted)
{
_lowerValue += valueDelta;
_lowerValue = BOUND(_lowerValue, _upperValue, _minimumValue);
}
if (_upperKnobLayer.highlighted)
{
_upperValue += valueDelta;
_upperValue = BOUND(_upperValue, _maximumValue, _lowerValue);
}
// 3. Update the UI state
[CATransaction begin];
[CATransaction setDisableActions:YES] ;
[self setLayerFrames];
[CATransaction commit];
return YES;
}
Here's my code in swift:
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
var touchPoint: CGPoint = touch.locationInView(self)
//Determine how much the user has dragged
var delta: CGFloat = touchPoint.x - previousTouchPoint.x
var valueDelta: CGFloat = (maximumValue - minimumValue) * delta / usableTrackLength
previousTouchPoint = touchPoint
//Update the values
if lowerKnobLayer.highlighted {
lowerValue += valueDelta
lowerValue = BOUND(upperValue, maximumValue, lowerValue) //this won't compile, there is no BOUND identifier
}
if upperKnobLayer.highlighted {
upperValue += valueDelta
upperValue = BOUND(_upperValue, _maximumValue, _lowerValue) //This doesn't work
}
//Update the UI State
CATransaction.begin()
CATransaction.setDisableActions(true)
self.setLayerFrames()
CATransaction.commit()
}
What's a BOUND macro? How do I do that in Swift?
EDIT BASED ON ANSWER BELOW:
lowerValue = min(max(lowerValue, upperValue), minimumValue)
upperValue = min(max(upperValue, maximumValue), lowerValue)
BOUND
is a self-declared macro in the code, that does MIN(MAX(VALUE, LOWER), UPPER)
where MIN
and MAX
are just C macros to get the min and max values between the values passed in. It gets the minimum value between the maximum value of value and lower, and upper (kind of confusing I guess).
Swift has these macros defined: Swift equivalent for MIN and MAX macros
Make a method that does what BOUND
is doing and call that instead, it is pretty well explained with examples in the above post.