我正在尝试使用相同的按钮将视图控制器设置为两个不同的视图控制器。但我希望segue是基于uitextfield中的信息完成的。例如,如果textfield包含正确的信息,那么我将需要segue执行segue到viewControllerA如果信息与我的字符串数组不匹配,ViewController将转到viewControllerB。
示例代码:
@IBOutlet var pcTextField: UITextField!
@IBOutlet var odButton: UIButton!
var activePcText = ["over", "left", "weak", "never"]
override func viewDidLoad() {
super.viewDidLoad()
pcTextField.delegate = self
let tapRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")
view.addGestureRecognizer(tapRecognizer)
odButton.hidden = true
self.pcTextField.addTarget(self, action: "pcEmpty", forControlEvents: UIControlEvents.EditingChanged)
}
@IBAction func odButton(sender: AnyObject) { }
我尝试将if语句实现为..
@IBAction func odButton(sender: AnyObject) {
if pcTextField.text!.containsString(activePcText) { }
}
我刚收到错误说:
Cannot convert value of type '[String]' to expected argument type 'String'
答案 0 :(得分:2)
@IBOutlet weak var pcTextField: UITextField!
let activePcText = ["over", "left", "weak", "never"]
@IBAction func buttonPressed(sender: UIButton) {
let text = pcTextField.text?.lowercaseString ?? ""
let destination = activePcText.map { $0.lowercaseString }.contains(text) ? "viewControllerA" : "viewControllerB"
performSegueWithIdentifier(destination, sender: self)
}
这使它不区分大小写。
答案 1 :(得分:0)
这是一个prepareForSegue
方法的例子,可以完成你想要做的事情
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueIdentifier" {
if myTextField.text = "words inside text field" {
let controller = segue.destinationViewController as! MyViewController
} else if myTextField.text = "different words in text field" {
let controller = segue.destinationViewController as! MyOtherViewController
}
}
}
因此,根据myTextField
内的文字,将对MyViewController
或MyOtherViewController
执行segue
然后在你想要触发segue的任何按钮的@IBAction
中添加performSegueWithIdentifier("segueIdentifier")