【发布时间】:2014-07-28 15:31:44
【问题描述】:
import UIKit
class KeyboardViewController: UIInputViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var nextKeyboardButton: UIBarButtonItem
var statusLabel: UILabel = UILabel()
var bottomBar : UIToolbar = UIToolbar()
var globeIcon : UIImage = UIImage(named: "globe-hover.png")
@IBOutlet var captureButton : UIBarButtonItem
@IBOutlet var libraryButton : UIBarButtonItem
override func viewDidLoad() {
super.viewDidLoad()
self.statusLabel.text="viewDidLoad() called"
// Perform custom UI setup here
self.nextKeyboardButton = UIBarButtonItem(image: self.globeIcon, style: .Plain , target: self, action: "advanceToNextInputMode")
self.captureButton = UIBarButtonItem(title: "Take Photo", style: .Plain, target: self, action: "captureClicked")
self.libraryButton = UIBarButtonItem(title: "Library", style: .Plain, target: self, action: "libraryClicked")
self.statusLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.statusLabel.sizeToFit()
var barItems : [UIBarButtonItem] = [self.nextKeyboardButton, self.captureButton, self.libraryButton]
self.bottomBar.items = barItems
self.view.addSubview(self.bottomBar)
self.view.addSubview(self.statusLabel)
var statusLabelLeftSideConstraint = NSLayoutConstraint(item: self.statusLabel, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0)
var statusLabelBottomConstraint = NSLayoutConstraint(item: self.statusLabel, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0)
self.view.addConstraints([statusLabelLeftSideConstraint, statusLabelBottomConstraint])
}
每次运行此程序时,我都会收到运行时错误:“致命错误:在展开可选值时意外发现 nil”,指的是位 var barItems : [UIBarButtonItem] = [self.nextKeyboardButton, self.captureButton, self.libraryButton],并且调试器指出 barItems 是一个空数组 (nil)。
这里发生了什么?为什么数组 barItems 不包含我的实例 UIBarButtonItem 变量?似乎 UIBarButtonItem 类型变量(captureButton、libraryButton 和 nextKeyboardButton)本身是 nil,但为什么呢?提前致谢!
【问题讨论】:
-
要让 barItems 数组接受 nil 值,请将类型更改为
[UIBarButtonItem?]。然后,您需要在使用if let concreteItem = barItems[n] { . code when not nil . } else { . code when nil . }构造之前显式检查每个数组项以查看它是否为 nil。 -
提示:在 viewWillAppear 中创建数组。