我收到此错误并且无法解决它...
我通过 UISegmentedControl 按钮更改将一个对象从 UIViewController 传递到另一个对象。下面是我用来传递对象的代码。它运行良好,我可以在控制台中打印对象详细信息。
@IBAction func switchViewAction(_ sender: UISegmentedControl) {
let vc = DirectionsViewController()
if let unwrappedRecipe = self.details
{
vc.customInit(recipes: unwrappedRecipe)
} else
{
print("it has no value!")
}
self.viewContainer.bringSubviewToFront(views[sender.selectedSegmentIndex])
}
但是,问题是当我尝试为标签设置值时,出现以下错误:
Unexpectedly found nil while implicitly unwrapping an Optional value
下面是我在 DirectionsViewController 中使用的代码
@IBOutlet weak var lblDirections: UILabel!
var recipe: Recipe? = nil
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func customInit(recipes: Recipe)
{
lblDirections.text = recipes.name
}
我研究了可选变量和强制变量,也尝试安全地解开变量,但没有成功。有人可以帮忙吗?
最佳答案
如果您有一个从 Storyboard 或 xib 加载的 IBOutlet
,则在调用 viewDidLoad
之前它是 nil
。因此,当在 viewDidLoad
之前调用 func customInit(recipes: Recipe)
时,lblDirections
为 nil
,并且因为它如果强行打开它会崩溃。您可以通过两种方式解决此问题:
丑陋但简单。当您第一次获取 View Controller 的
view
时,会调用viewDidLoad
,因此您可以在vc 之前添加
在_ = vc.view
.customInit(recipes: unwrappedRecipe)func switchViewAction(_ sender: UISegmentedControl)
中。我不建议使用它的生产代码,但您可以使用它来测试一切是否正常工作。因为您使用的是 xib,所以您可以初始化 View Controller 并提供自定义 init(甚至您的方法名称也表明了这一点:
customInit
)。要拥有正确的 View Controller 初始化,您需要使用:
class DirectionsViewController: UIViewController {
let recipe: Recipe
@IBOutlet weak var lblDirections: UILabel!
init(recipe: Recipe) {
self.recipe = recipe
let classType = type(of: self)
let bundle = Bundle(for:classType)
super.init(nibName: "DirectionsViewController", bundle: bundle) //provide your nib filename
}
override func viewDidLoad(){
super.viewDidLoad()
//code from func customInit(recipes: Recipe)
lblDirections.text = recipe.name
}
@available(*, unavailable, message: "use init(recipe: Recipe)")
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
fatalError("init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) has not been implemented")
}
@available(*, unavailable, message: "don't use sotryboard! use nib and init(recipe: Recipe)")
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
您无法提供可选的Recipe
或在创建后更新它,但这使代码变得不那么复杂。它还假设您的 xib 文件名为 DirectionsViewController.xib
(如果不是,您需要在 super.init(nibName: "DirectionsViewController", bundle: bundle)
行中更改它)。
您也可以使用我的微图书馆 NibBased需要编写的代码少一点。使用该库时,您的代码应该是:
import NibBased
class DirectionsViewController: NibBaseViewController {
let recipe: Recipe
@IBOutlet weak var lblDirections: UILabel!
init(recipe: Recipe) {
self.recipe = recipe
super.init()
}
override func viewDidLoad() {
super.viewDidLoad()
lblDirections.text = recipe.name
}
}
关于swift - 无法设置 UILabelView.Text 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59422713/