【发布时间】:2015-11-06 16:41:25
【问题描述】:
我正在通过this tutorial 了解如何制作双滑块,同时还学习如何从 ObjC 转换为 Swift(我只知道 Swift,但我正在学习一点关于 ObjC 的知识),进展顺利,但我我被困在这一点上,试图将这部分翻译成 swift。一方面我不知道 BOUND 宏是什么,它不在像 this one 这样的任何指南中,另一方面我不知道如何将它翻译成 Swift。
这是目标 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;
}
这是我的 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()
}
什么是 BOUND 宏?我如何在 Swift 中做到这一点?
根据以下答案进行编辑:
lowerValue = min(max(lowerValue, upperValue), minimumValue)
upperValue = min(max(upperValue, maximumValue), lowerValue)
【问题讨论】:
标签: objective-c swift code-translation