2016-12-27 14 views
2

多くのチェックボックスを使用するプロジェクトで作業します。私は以下のような解決策を見つけましたが、私はこれが正しい方法ではないことを知っています。チェックボックスを使用する最善の方法 - IOS swift

@IBAction func btn_box(sender: UIButton) { 
    if (btn_box.selected == true) 
    { 
     btn_box.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal) 

      btn_box.selected = false; 
    } 
    else 
    { 
     btn_box.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Normal) 

     btn_box.selected = true; 
    } 
} 

誰も私のプロジェクトで20個以上のチェックボックスを持つ正しい方法を教えてもらえますか?

フォームと設定目的でチェックボックスを使用します。

ありがとうございました。

+0

Tableviewセルを使用していますか? – Amanpreet

+0

いいえ、私はフォームと設定の目的で使用します – Akram

+0

このリンクに従ってください:http://stackoverflow.com/questions/40782238/how-to-show-checkmark-in-tableview-swift/40782436#40782436 –

答えて

14

ありCheckbox controlの多くがあるか、この単純な方法でそれを行う:ストーリーボード用

  1. ボタンの選択した画像を設定:

    enter image description here

  2. 設定し、ボタンのデフォルトイメージ:プログラムのために

    enter image description here

btn_box.setBackgroundImage(UIImage(named: "box"), for: .normal) 
btn_box.setBackgroundImage(UIImage(named: "checkBox"), for: .selected) 

とボタンアクションで:

@IBAction func btn_box(sender: UIButton) { 
    sender.isSelected = !sender.isSelected 
} 
4

それぞれのボタンを確認する代わりに、一般的な方法でこれを処理してください。同じIBActionメソッドにすべてのボタンを設定し、そのように実装:

@IBAction func btn_box(sender: UIButton) 
{ 
    // Instead of specifying each button we are just using the sender (button that invoked) the method 
    if (sender.selected == true) 
    { 
     sender.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal) 
     sender.selected = false; 
    } 
    else 
    { 
     sender.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Normal) 
     sender.selected = true; 
    } 
} 
1

あなたは最も有用それ以下のアプローチを使用することができます:あなたのStoryBoardで またはViewDidLoadUIButtonのためにイメージを割り当てる:この後

checkBoxButton.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal) 
checkBoxButton.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Selected) 

をご@IBAction方法でちょうど次のコードを実装:

@IBAction func btn_box(sender: UIButton) { 
    sender.selected = !sender.selected 
} 

これはトリックを行います。

0

これを試してください。

btn.setImage(UIImage(named: "uncheckImage"), for: UIControlState.normal) 
btn.setImage(UIImage(named: "checkImage"), for: UIControlState.selected) 

@IBAction func btn_box(sender: UIButton) { 

    if btn.isSelected == true { 

      btn.isSelected = false 
    } 
    else { 

      btn.isSelected = true 
    } 
} 
+1

または、単にbutton.isSelected =!button.isSelected – FrostyL

関連する問題