2016-10-03 5 views
0

私はSegmentedControlを持っています。ユーザーがクリックすると、値を変更するかどうかを確認する確認ダイアログボックスが表示されます。 「キャンセル」をクリックすると、SegmentedControl値の変更を取り消したいと思います。事前に確認ダイアログボックスに基づいてSegmentedControlインデックスが変更されないようにするにはどうすればよいですか?

@IBAction func indexChanged(_ sender: UISegmentedControl) { 
    let refreshAlert = UIAlertController(title: "Update", message: "Sure you wanna change this?", preferredStyle: UIAlertControllerStyle.alert) 

    refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in 

    })) 

    refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in 
     // Nothing 
    })) 

    present(refreshAlert, animated: true, completion: nil) 
} 

ありがとう:

これは私が持っているコードセグメントです。

答えて

0

最後に選択したインデックスを保持する変数を保持することをお勧めします。キャンセルの完了ハンドラで、セグメントの選択されたインデックスを変数の値に設定します。 Okの補完ハンドラでは、変数を現在選択されているインデックスで更新します。

0

スイッチがうまく見えるように、lastSelectedIndexをインスタンス変数に格納し、選択したインデックスをすぐにこの値に設定することをお勧めします。ユーザーがOkをタップした場合のみ、実際のスイッチを実行します。あなたが検証を行うことができます前に、このsegmentControlが既に反応している任意のコードを観察(KVO)

var lastSelectedIndex = 0 
@IBOutlet weak var segmentedControl: UISegmentedControl! 

@IBAction func indexChanged(_ sender: AnyObject) { 
    let newIndex = self.segmentedControl.selectedSegmentIndex; 
    self.segmentedControl.selectedSegmentIndex = lastSelectedIndex 

    let refreshAlert = UIAlertController(title: "Update", message: "Sure you wanna change this?", preferredStyle: .alert) 

    refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { [weak self, newIndex] (action: UIAlertAction!) in 
     self!.segmentedControl.selectedSegmentIndex = newIndex 
     self!.lastSelectedIndex = newIndex 
    })) 

    refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) 

    present(refreshAlert, animated: true, completion: nil) 
} 
+0

しかし、もちろん:

は、以下の完全なコードを参照してください。さらに、 'self.segmentedControl.selectedSegmentIndex = lastSelectedIndex'で直ちに選択したインデックスをリセットするので、KVOオブザーバは2回トリガされ、ユーザが後でOKを選択した場合は3回目にトリガされます。 – Yohst

関連する問題