3
- (void)setStrokeLabel:(BOOL)strokeLabel
{
    _strokeLabel = strokeLabel;

    if (_strokeLabel) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(setStrokeThrough) userInfo:nil repeats:NO];
    } else {
        [self cancelStrokeThrough];
    }
}

- (void)setStrokeThrough
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];

    for (NSUInteger i = 1; i <= [attributedString length]; i++) {
        [attributedString addAttribute:NSStrikethroughStyleAttributeName
                                 value:[NSNumber numberWithInt:1]
                                 range:NSMakeRange(0, i)];
        self.attributedText = attributedString;
    }
}

- (void)cancelStrokeThrough
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [attributedString removeAttribute:NSStrikethroughStyleAttributeName
                                range:NSMakeRange(0, [attributedString length])];
    self.attributedText = attributedString;

}

私はアニメ化したいstrike-through、todo done animationのように。タイマーを設定したので、タイマーは文字ごとにストークを表示する方法のみを処理しますか??

4

1 に答える 1

2

これを行う 2 つの関数を次に示します。

    BOOL setStrokethrough(UILabel *label, NSRange range)
    {
        if (range.location >= [label.attributedText length])
            return FALSE;

        if (range.location + range.length > [label.attributedText length])
            range.length = [label.attributedText length] - range.location;

        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];

        [attributedString addAttribute:NSStrikethroughStyleAttributeName
                                 value:@(NSUnderlineStyleSingle)
                                 range:range];

        label.attributedText = attributedString;
        return TRUE;
    }

    -(void)animateSetStrokethroughDuration:(float)duration
    {
        __block float const stepDuration = 0.1;
        float steps = duration / stepDuration;
        __block NSRange range = NSMakeRange(0, ceil((float)[self.label.attributedText length] / steps));

        void (^__block fn)();
        void (^__block __weak weakfn)();

        weakfn = fn = ^(){
            if (!setStrokethrough(self.label, range))
                return;
            range = NSMakeRange(range.location + range.length, range.length);
            [self performBlock:weakfn afterDelay:stepDuration];
        };
        fn();
    }

ノート

  1. アニメーションの時間を制限するために、キャラクターごとではなく、キャラクターのブロックごとにアニメートします。文字列が長いほど、文字のブロックが長くなります。
  2. __block __弱いビジネスはここで説明されています
  3. self performBlock は、Mike Ashによる NSObject の拡張であり、ここでも
  4. コードは、self.label メンバーが定義されていることを前提としています
于 2013-05-01T07:10:34.460 に答える