2016-10-03 26 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一個實例變量,然後立即將所選擇的指數爲該值。只有當用戶點擊好吧,你做的實際開關。

請參見下面全碼:

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

當然,任何代碼觀察(志願)這個segmentControl已經反應,你可以做驗證之前,但是。此外,由於您立即使用'self.segmentedControl.selectedSegmentIndex = lastSelectedIndex'重置所選索引,因此如果用戶以後選擇了OK,KVO觀察者將被觸發兩次,並可能第三次觸發。 – Yohst