gpt4 book ai didi

ios - 可选解包失败,当 socket 连接正确时

转载 作者:搜寻专家 更新时间:2023-11-01 07:28:26 25 4
gpt4 key购买 nike

我正在开发简单的应用程序,用户可以在其中登录并从网络上阅读文章。我最近添加了一段代码,在处理转场时在第二个 View 中设置标题,但不幸的是我在第二页的标题为零。我在 Storyboard中有一个对象正确连接到 View Controller 中的变量,我检查了两次。我不知道该怎么办,也许我没有正确打开包装。

代码:

import UIKit

class MainViewController: UIViewController, UITabBarDelegate, UITabBarControllerDelegate, UIToolbarDelegate {
@IBOutlet var titleLabel: UILabel!

@IBOutlet var newsBar: UIToolbar!
@IBOutlet var accountBar: UITabBar!

override func viewDidLoad() {
super.viewDidLoad()

accountBar.delegate = self
newsBar.delegate = self

titleLabel.backgroundColor = UIColor(netHex: 0x00B0E4)

titleLabel.textColor = UIColor.whiteColor()
titleLabel.font = UIFont.boldSystemFontOfSize(16.0)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
return true
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let next: SectionViewController = segue.destinationViewController as! SectionViewController

switch segue.identifier! {
case "hardwareSectionSegue":
next.titleLabel.text = "Rubrika o hardwaru"

case "softwareSectionSegue":
next.titleLabel.text = "Rubrika o softwaru"

case "webSectionSegue":
next.titleLabel.text = "Rubrika o webových technologiích"

case "programmerSectionSegue":
next.titleLabel.text = "Rubrika o programování"

case "mobileSectionSegue":
next.titleLabel.text = "Rubrika o mobilních zažízeních"

default:
next.titleLabel.text = "Rubrika nenalezena"

next.titleLabel.backgroundColor = UIColor.redColor()
}
}

@IBAction func unwindSegue(unwindSegue: UIStoryboardSegue) {}
}

异常发生在我尝试为 next.titleLabel.text 赋值的第一种情况下。它说 titleLabel 是 nil,它应该不是。

SectionViewController:

import UIKit

class SectionViewController: UIViewController {
@IBOutlet var titleLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

我很确定这是由类型转换引起的,但是如果 segue 甚至不知道下一个 View 的类型是什么,我该如何正确设置属性?

最佳答案

我知道你想做什么,但恐怕 iOS 不允许你那样做。在您的 prepareForSegue() 方法中,您试图修改通过直接设置文本值创建的 View Controller 。

iOS 会尽可能延迟加载,这意味着此时在您的程序中实际上尚未创建标签——它实际上是nil。如果您在该行放置断点,您应该能够在调试器窗口中运行 po next.titleLabel 以查看 nil 返回。如果您首先运行 po next.view,它将强制 iOS 创建 View 及其所有 subview ,此时再次运行 po next.titleLabel 将按您预期的那样工作。

如果您尝试在 Xcode 中创建模板主从应用程序项目,您将看到正确的解决方案:在新 View Controller 中设置一个属性,然后将该值传输到 viewDidLoad() 中的标签>.

总结:当您从 View Controller A 导航到 View Controller B 时,不要让 A 尝试配置 B 的 UI。相反,向 B 发送它需要的值,并让 B 自行配置。

关于ios - 可选解包失败,当 socket 连接正确时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34341523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com