Objective-C转换为Swift:绑定宏?

时间:2015-11-06 16:41:26

标签: objective-c swift code-translation

我正在通过this tutorial关于如何制作双滑块同时学习如何从ObjC转换为Swift(我真的只知道Swift,但我正在学习一些关于ObjC的东西),它很顺利但我仍然坚持这一点,试图将这部分转化为迅速。我不知道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)

1 个答案:

答案 0 :(得分:2)

BOUND是代码中的一个自我声明的宏,MIN(MAX(VALUE, LOWER), UPPER)

其中MINMAX只是C宏,用于获取传入的值之间的最小值和最大值。它获取值和最大值之间的最小值和上限(种类)令人困惑的我猜)。

Swift定义了这些宏: Swift equivalent for MIN and MAX macros

创建一个执行BOUND正在执行的操作的方法,然后调用它,上面的帖子中的示例很好地解释了它。