user
user

Reputation: 455

Swift animate strikethrough uilabel

I'm trying to animate a strike through animate. The only help I could find was this UIFont: how to animate strikethrough and match font style? but its Objective-C I'm trying for a result something like this https://dribbble.com/shots/3167358-Microinteractions-for-to-do-list-app. But can't figure out how to animate the strikethrough.

 guard let postsText = post?.post else { return }

        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: postsText)
        attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: NSMakeRange(0, attributeString.length))
        postLabel.attributedText = attributeString

Upvotes: 0

Views: 837

Answers (2)

chr0x
chr0x

Reputation: 1251

I've created a library that creates this effect using Bezier Path, animating the strikethrough. You can find the code here:

https://github.com/chrsp/StrikethroughLabel

For the record, this class shows how you can do that:

https://github.com/chrsp/StrikethroughLabel/blob/master/StrikethroughLabel/StrikethroughLabel.swift

Upvotes: 2

Sam Furlong
Sam Furlong

Reputation: 106

self.mylabel.attributedText = nil;
CATransition *transition = [CATransition new];
transition.delegate = self;
transition.type = kCATransitionFromLeft;
transition.duration = 2.0f;
self.mylabel.attributedText = strikeThroughText;
[self.mylabel.layer addAnimation:transition forKey:@"transition"];

So I am posting the original objective C code for reference. Really this is just a matter of translating the objective C code to Swift, which is possible because under the hood Swift can use the same core animation api that objective C can.

I used the apple docs for reference.

https://developer.apple.com/documentation/quartzcore/catransition

let transition = CATransition()
transition.type = CATransitionType.moveIn
transition.subtype = CATransitionSubtype.fromLeft
transition.duration = 2.0
label.attributedText = strikeThroughText
label.layer.add(transition, forKey: kCATransition)

This should achieve something like what what the objective C code in the other post does. You will likely have to modify it, but it should get you started on the correct path. I would play around with the different CATransitionType and see what can be achieved.

Upvotes: 1

Related Questions