2016-09-10 11 views
2

私はUIButtonを持っています。これを押すとタイトルと色が切り替わります。ボタンには、毎日、毎月、毎年の3つの状態があります。UIButtonを使用して3つの状態を切り替える

今私はそれがエレガントないないようです。このソリューションを持っている:

if sender.currentTitle == "Daily" { 
    sender.setTitle("Monthly", for: .normal) 
    sender.setTitleColor(UIColor(hex: "FB967F"), for: .normal) 
} else if sender.currentTitle == "Monthly" { 
    sender.setTitle("Yearly", for: .normal) 
    sender.setTitleColor(UIColor(hex: "A395CE"), for: .normal) 
} else if sender.currentTitle == "Yearly" { 
    sender.setTitle("Daily", for: .normal) 
    sender.setTitleColor(UIColor(hex: "75CFF8"), for: .normal) 
} 

はスウィフトでこれを行うために、より便利な方法はありますか?

答えて

2

、カウンタをインクリメント(モジュロ演算子を介して範囲0 ... 2でそれを維持)と配列

からタイトルや色値を取得 counter変数と二つの配列

var counter = 0 
let titleArray = ["Daily", "Monthly", "Yearly"] 
let colorArray = ["FB967F", "A395CE", "75CFF8"] 

を宣言

counter = (counter + 1) % titleArray.count 
sender.setTitle(titleArray[counter], for: .normal) 
sender.setTitleColor(UIColor(hex: colorArray[counter]), for: .normal) 
3

enumを使用 状態を維持するのに最適です。コードをきれいにして読みやすくします。

enum ButtonState { 
    case daily 
    case monthly 
    case yearly 

    mutating func next(forButton button:UIButton) { 
     switch (self) { 
     case .daily: 
      self = .monthly 
     case .monthly: 
      self = .yearly 
     case .yearly: 
      self = .daily 
     } 

     button.setTitle(self.getTitle(), forState: .Normal) 
     button.setTitleColor(UIColor(hex: self.getTitleColorHex()), forState: .Normal) 
    } 

    private func getTitle() -> String { 
     switch (self) { 
     case .daily: 
      return "Daily" 
     case .monthly: 
      return "Monthly" 
     case .yearly: 
      return "Yearly" 
     } 
    } 

    private func getTitleColorHex() -> String { 
     switch (self) { 
     case .daily: 
      return "FB967F" 
     case .monthly: 
      return "A395CE" 
     case .yearly: 
      return "75CFF8" 
     } 
    } 
} 

var currentButtonState = ButtonState.daily 

func changeButtonState(forButton button:UIButton) { 
    currentButtonState.next(forButton: button) 
} 
+0

10行のコードを40に変換しました。読みやすくなっていますか? :) – Grimxn

+2

笑。その抽象概念については、2つのパラメータの配列を作成することができます。結果をフェッチするためにenumのrawvalueを使用すると、半分に減らすことができます。 私はちょうどそれを完全に書いて、行っている。 ビューコントローラのコードについて考えてみましょう。これは2行です。 ;)、また州全体の実装を抽象化してカプセル化する機能も備えています。 – vj9

0

私は本当にあなたのコードがそう無粋だとは思わない - それがあった場合には、三状態が、しかし、(実際には無粋コードの問題である)、彼らが読みにくいほど複雑ではありません3つ以上のあなたは間違いなくもっと素敵なものを望んでいます。状態遷移辞書を使用するとどうなりますか:

func newButtonState(sender: UIButton) { 
    let buttonDict = ["Yearly": (UIColor.red, "Daily"), 
         "Monthly": (UIColor.green, "Yearly"), 
         "Daily": (UIColor.yellow, "Monthly")] 
    if let t = sender.currentTitle, let n: (UIColor, String) = buttonDict[t] { 
     sender.setTitle(n.1, for: .normal) 
     sender.setTitleColor(n.0, for: .normal) 
    } 
} 
+0

関数を呼び出すだけで、ボタンの "state"はそのタイトルであり、関数はタイトルを循環します... – Grimxn

関連する問題