我有一個segmentedControl給一個文本字段的字符串。另外我還有2個textfields。一個用於用戶輸入,另一個用於從分段控制文本字段和用戶輸入文本字段進行計算。當segmentedcontrolindex發生變化時,如何自動更新計算文本字段。 對於用戶輸入文本字段textfielddidchangemethod的作品。由於 segmentedcontrol/textfield/DidChange
@IBOutlet weak var segmentedcontrol: UISegmentedControl!
@IBOutlet weak var textf: UITextField!
@IBOutlet weak var textf1: UITextField!
@IBOutlet weak var textf2: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textf.delegate = self
textf1.delegate = self
textf2.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func textf1(sender: AnyObject) {
let result = (textf.text! as NSString).doubleValue * (textf2.text! as NSString).doubleValue
textf1.text = String(format:"%.2f", result)
}
@IBAction func segmentedcontrolAction(sender: AnyObject) {
if(segmentedcontrol.selectedSegmentIndex == 0)
{
textf2.text = "5";
}
else if(segmentedcontrol.selectedSegmentIndex == 1)
{
textf2.text = "10";
}
else if(segmentedcontrol.selectedSegmentIndex == 2)
{
textf2.text = "15";
}
}
你不需要'IBOutlet'的分段控制。它在'segmentedcontrolAction'中作爲參數'sender'傳遞。你可以優化你的代碼寫'switch sender.selectedSegmentIndex {case 0:...}'或甚至'textf2.text =「\((sender.selectedSegmentIndex + 1)* 5)」' – vadian