我想要一行代码,每当用户将位置切换到卡萨布兰卡时,它们都会更改情节提要,但由于某些原因,我编写的代码不正确。怎么了?
导入UIKit
ViewController类:UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet weak var locationlabel: UILabel!
@IBOutlet weak var locationpicker: UIPickerView!
let locations = ["Select your location", "Casablanca"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return locations[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return locations.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
locationlabel.text = locations[row]
}
if (locationlabel.text == "Casablanca") {
let storyboard = UIStoryboard(name: "NextBoard1", bundle: nil)
let vc = storyboard.instantiateInitialViewController()!
present(vc, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
答案 0 :(得分:0)
您需要以编程方式更改情节提要,而不仅仅是执行顺序。
假设您有另一个名为“ NextBoard1”的情节提要,并且此情节提要的开头为UIViewController
,则可以尝试以下操作:
if (locationlabel.text == "Casablanca") {
let storyboard = UIStoryboard(name: "NextBoard1", bundle: nil)
let vc = storyboard.instantiateInitialViewController()!
present(vc, animated: true, completion: nil)
}
编辑-示例代码
考虑此设置:
Main.storyboard具有一个具有自定义类ViewController
的视图控制器,该类具有一个标签和一个选择器:
NextBoard1.storyboard具有一个初始视图控制器:
ViewController.swift
import UIKit
class ViewController: UIViewController,UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var locationlabel: UILabel!
@IBOutlet weak var locationpicker: UIPickerView!
let locations = ["Select your location", "Casablanca"]
override func viewDidLoad() {
super.viewDidLoad()
locationpicker.delegate = self
locationpicker.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return locations[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return locations.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
locationlabel.text = locations[row]
if (locationlabel.text == "Casablanca") {
let storyboard = UIStoryboard(name: "NextBoard1", bundle: nil)
let vc = storyboard.instantiateInitialViewController()!
present(vc, animated: true, completion: nil)
}
}
}
输出