ios - 从另一个类访问 UISegmentedControl @IBOoutlet

标签 ios swift xcode uisegmentedcontrol iboutlet

我有一个 Table View Controller,旨在用作设置页面,它包含一个具有 3 个段的 UISegmentedControl:

class SettingsView: UITableViewController {

@IBOutlet weak var ButtonSelection: UISegmentedControl!

//Index 0 is default selection (first)

override func viewDidLoad() {
    super.viewDidLoad()
    // some code   
}

另外,我有一个 Navigation View Controller,它控制 3 个不同的 UIViewController 和相应的 Storyboard ID(“first”、“second”和“third”)。

我正在尝试准备导航 View Controller 以根据 UISegmentedControl 选择呈现适当的 View Controller 。但是,我不断收到“ fatal error :在展开可选值时意外发现 nil”并且不确定如何解决。

这是我试过的:

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")

谁能给我指出正确的方向,好吗?提前致谢!

最佳答案

你有几个问题。

问题 1:UITableViewController 未设置为承载任何表格 View 。它的内容 View 被锁定为 TableView 。如果您想要一个由 UITableViewController 管理的 TableView ,并且您想要 View Controller 中的其他内容,则需要使 UITableViewController 成为另一个 View Controller 的子级。好消息是,使用容器 View 和嵌入 segue 非常容易。

问题 2 是一个“不要那样做”的问题。您应该将 View Controller 的 View 视为私有(private)的。另一个 View Controller 不应尝试查看或更改另一个 View Controller 的分段控件。 (这是糟糕的设计,它也可能导致像您描述的那样崩溃,因为您无法确定是否已经加载了另一个 View Controller 的 View 。)相反,您应该向 View 添加一个整数属性“selectedIndex”包含分段控件的 Controller ,并使用它来读/写选定的段。 (在 OOP 术语中,您将一个公共(public)接口(interface)添加到 View Controller 的“契约(Contract)”以公开您想要公开的功能,然后添加提供该接口(interface)的代码。)

关于ios - 从另一个类访问 UISegmentedControl @IBOoutlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44359940/

相关文章:

swift - 根据 TableView 中的项目数使动态 UI 按钮出现和消失

ios - Xcode 免费配置 : The 'Apple Push Notification' feature is only available to users enrolled in Apple Developer Program

iphone - 使用 EXIF 将 UIImage 写入保存的相册

ios - ios使用描述的edit-config : doc. find is not a function

ios - 事件指示器动画不起作用 - Swift

python - 在 ios 中运行一个简单的 python 脚本

ios - 当使用特定队列调用 dispatch_async 时的符号断点

ios - 如何在谷歌地图中点击标记

ios - 向上舍入到字典中最接近的整数键值 [Swift/iOS]

ios - 是否可以知道 QLPreviewController 何时到达文档末尾?