【发布时间】:2017-03-19 18:05:30
【问题描述】:
我真的很难将一个数组的内容从视图控制器传递到另一个以设置 nscombobox 的内容。我已经尝试了我能想到的一切,为segue、init做准备;但似乎没有任何效果。 程序流程如下:用户在文本字段中输入一个数字,并在此基础上创建一个具有数字大小的数组。一旦用户按下一个按钮,下一个 VC 就会出现,它有一个组合框,并且在该组合框内需要出现这些数字。我所有的尝试都导致传递一个空数组。有人可以花点时间帮助我。我确定我犯了一个愚蠢的错误,但无法弄清楚是什么。 代码清单如下: 接受用户输入的类。在这个阶段,我试图在下一堂课中传递数组的内容,因为我放弃了为 segue 做准备,因为那个因为 nil 错误而崩溃。请注意,代码清单中未注释为 segue 准备,仅用于此处的格式化目的。我的程序被注释掉了,因为我现在正在使用 perform segue。 任何解决方案都会很好。谢谢你。
import Cocoa
class SetNumberOfFloorsVC: NSViewController {
//MARK: - Properties
@IBOutlet internal weak var declaredNumber: NSTextField!
internal var declaredFloorsArray = [String]()
private var floorValue: Int {
get {
return Int(declaredNumber.stringValue)!
}
}
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction private func setNumberOfFloors(_ sender: NSButton) {
if declaredNumber.stringValue.isEmpty {
let screenAlert = NSAlert.init()
screenAlert.messageText = "Please specify the number of floors!"
screenAlert.addButton(withTitle: "Got it!")
screenAlert.runModal()
} else if floorValue == 0 || floorValue < 0 {
let screenAlert = NSAlert.init()
screenAlert.messageText = "Please input a correct number of floors!"
screenAlert.addButton(withTitle: "Got it!")
screenAlert.runModal()
} else {
for i in 0...floorValue - 1 {
declaredFloorsArray.append(String(i))
}
print("\(declaredFloorsArray)")
let declareNumberOfRoomsVC = SetNumberOfRoomsForFloorVC(boxData: declaredFloorsArray)
declareNumberOfRoomsVC.boxData = declaredFloorsArray
performSegue(withIdentifier: "set number of rooms", sender: self)
}
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if segue.identifier == "set number of rooms" {
if let addRoomsVC = segue.destinationController as? SetNumberOfRoomsForFloorVC {
addRoomsVC.floorBox.addItems(withObjectValues: declaredFloorsArray)
}
}
}
}
这是下一个带有组合框的 VC 的类:
import Cocoa
class SetNumberOfRoomsForFloorVC: NSViewController, NSComboBoxDelegate, NSComboBoxDataSource {
//MARK: - Properties
@IBOutlet internal weak var floorBox: NSComboBox!
@IBOutlet private weak var numberOfRoomsTxtField: NSTextField!
internal var boxData = [String]()
//MARK: - Init
convenience init(boxData: [String]) {
self.init()
self.boxData = boxData
}
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
floorBox.usesDataSource = true
floorBox.dataSource = self
floorBox.delegate = self
print("\(boxData)")
}
@IBAction private func setRoomsForFloor(_ sender: NSButton) {
}
//MARK: - Delegates
func numberOfItems(in comboBox: NSComboBox) -> Int {
return boxData.count
}
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return boxData[index]
}
}
【问题讨论】:
-
内部变量 boxData = [String]()? floorBox.usesDataSource = true?您所要做的就是将一个数组传递给组合人。