I have Table View Controller, intended to serve as a settings page, that contains a UISegmentedControl with 3 segments:
class SettingsView: UITableViewController {
@IBOutlet weak var ButtonSelection: UISegmentedControl!
//Index 0 is default selection (first)
override func viewDidLoad() {
super.viewDidLoad()
// some code
}
Separately, I have a Navigation View Controller that controls 3 different UIViewControllers with corresponding Storyboard IDs ("first", "second", and "third").
I'm trying to prepare the Navigation View Controller to present the appropriate View Controller based on UISegmentedControl selection. However, I keep getting "fatal error: unexpectedly found nil while unwrapping an Optional value" and not sure how to resolve.
This is what I have tried:
class NavViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
if SettingsView().ButtonSelection.selectedSegmentIndex == 0 {
print ("first segment is selected")
let destinationController = storyboard?.instantiateViewController(withIdentifier: "first")
else if SettingsView().ButtonSelection.selectedSegmentIndex == 1 {
print ("second segment is selected")
let destinationController = storyboard?.instantiateViewController(withIdentifier: "second")
else if SettingsView().ButtonSelection.selectedSegmentIndex == 0 {
print ("third segment is selected")
let destinationController = storyboard?.instantiateViewController(withIdentifier: "third")
Could anyone point me in the right direction, please? Thanks in advance!
答案 0 :(得分:0)
你有几个问题。
问题1:UITableViewController未设置为承载任何但表视图。它的内容视图被锁定为表视图。如果您想要一个由UITableViewController
管理的表视图,并且您想要视图控制器中的其他内容,则需要使UITableViewController
成为另一个视图控制器的子级。好消息是使用容器视图和嵌入segue非常容易。
问题2是“不要那样做”的问题。您应该将视图控制器的视图视为私有。另一个视图控制器不应该尝试查看或更改另一个视图控制器的分段控件。 (这是糟糕的设计,它也可能导致像你描述的那样崩溃,因为你无法确定是否已经加载了其他视图控制器的视图。)相反,你应该在视图中添加一个整数属性“selectedIndex”包含分段控件的控制器,并使用它来读/写所选段。 (在OOP术语中,您向视图控制器的“契约”添加公共接口,该公共接口公开您要公开的功能,然后添加提供该接口的代码。)