はじめに
今回はLTMorphingLabelというライブラリが面白そうなので使ってみました。
LTMorphingLabelとは
ラベルのテキスト変更時にエフェクトをつけてくれるライブラリです。
https://github.com/lexrus/LTMorphingLabel
作者のgithubにエフェクトのサンプルがあるのですが、見ているだけで試してみたい欲に駆られますね。
準備
今回はCocoaPodsで追加します。
1 | pod'LTMorphingLabel',:git=>'https://github.com/lexrus/LTMorphingLabel.git',:branch=>'swift3' |
実装
まずはLTMorphingLabelをimportします。
1 | importLTMorphingLabel |
StoryboardにUILabelを適当に用意し、ClassにLTMorphingLabelを指定してください。
それをIBOutlet接続します。
1 | @IBOutlet weakvarmorphingLabel:LTMorphingLabel! |
エフェクトの定義を行います。
1 | morphingLabel.morphingEffect=.evaporate |
エフェクトの種類、サンプルに関しては作者のgithubを参照してください。
これでmorphingLabelのtextを変更するとエフェクトがかかるようになります。
これだけだとイマイチエフェクトの切り替わりを実感できないので、TimerでmorphingLabelのtextを更新するようにしてみたいと思います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | @IBOutlet weakvarmorphingLabel:LTMorphingLabel! //表示制御用タイマー private vartimer:Timer? //String配列のindex用 private varindex:Int=0 //表示するString配列 private lettextList=["シンプルであることは、","複雑であることよりも","難しい"] overridefuncviewDidLoad(){ super.viewDidLoad() // エフェクトの定義 morphingLabel.morphingEffect=.evaporate } overridefuncviewDidAppear(_animated:Bool){ super.viewDidAppear(animated) //タイマーの追加 timer=Timer.scheduledTimer(timeInterval:3.0, target:self, selector:#selector(update(timer:)),userInfo:nil, repeats:true) timer?.fire() } overridefuncviewDidDisappear(_animated:Bool){ super.viewDidDisappear(animated) timer?.invalidate() } funcupdate(timer:Timer){ //ここでtextの更新 morphingLabel.text=textList[index] index+=1 ifindex>=textList.count{ index=0 } } |
これでLTMorphingLabelのエフェクトを堪能できると思います。
実装も簡単ですし、見た目も素晴らしいので色々使ってみたいですね。