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)本身都是零,但为什么呢?提前谢谢!
答案 0 :(得分:1)
来自目标C的许多对象都是隐式解包的选项,因为目标C指针不具有swift提供的相同类型安全性。
您在此行收到错误,因为类型[UIBarButtonItem]
不允许数组中的nil值,而您在数组中放置的某些值是 {{1} }。
nil
我要做的第一件事就是让调试变得更简单,就是在这些值的原始实例化中添加类型(你 期望var barItems : [UIBarButtonItem] = [self.nextKeyboardButton, self.captureButton, self.libraryButton]
):
nil
objective-c中的一些初始化器返回nil表示初始化失败,也许这就是这种情况?如果是,则在添加类型注释后会出现其他错误。你能发布那个错误吗?