无法设置 UILabelView.Text 值



>我收到此错误,无法解决...

我正在通过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
}

我研究了可选和强制变量,也试图安全地解开变量,但没有运气。有人可以帮忙吗?

如果你有一个从情节提要或 xib 加载的IBOutlet,则会nil,直到调用viewDidLoad。所以当func customInit(recipes: Recipe)viewDidLoad之前被调用时,lblDirectionsnil的,因为它是强制展开的,所以它会崩溃。您可以通过两种方式解决此问题:

  1. 丑陋但容易。viewDidLoad是在您第一次view视图控制器时调用的,因此您可以在func switchViewAction(_ sender: UISegmentedControl)vc.customInit(recipes: unwrappedRecipe)之前添加_ = vc.view。我不建议使用它的生产代码,但您可以使用它来测试一切是否正常。

  2. 因为您使用的是 xib,所以您可以初始化视图控制器并提供自定义 init(甚至您的方法名称也表示它:customInit(。要有一个合适的视图控制器init,你需要使用:


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
}
}

将值传递给 DirectionsViewController 和DirectionsViewController 调用的 viewDidLoad 方法中的配方变量

lblDirections.text =  recipe.name

最新更新