我有一个组合框,里面有一些数字,基于数组的长度是参数。我拿那个数组并设置字典的键。我的问题是如何获取用户从组合框中选择的数字,将其与字典中的键匹配并从不同的文本字段更新值。到目前为止,我已经设置了按键,但是我已经陷入了下一步。请参阅下面的代码清单。先感谢您。
class SetNumberOfRoomsForFloorVC: NSViewController, NSComboBoxDelegate, NSComboBoxDataSource {
//MARK: - Properties
@IBOutlet private weak var floorBox: NSComboBox!
@IBOutlet private weak var numberOfRoomsTxtField: NSTextField!
private var floorBoxData = [String]()
private var roomsForFloor = [String: String]()
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
floorBoxData = representedObject as! [String]
floorBox.usesDataSource = true
floorBox.delegate = self
floorBox.dataSource = self
setTheKeys(floorsValue: floorBoxData)
print("\(roomsForFloor.keys.sorted())")
}
private func setTheKeys(floorsValue: [String]) {
for i in 0...floorsValue.count - 1 {
roomsForFloor[String(i)] = ""
}
}
@IBAction private func setRoomsForFloor(_ sender: NSButton) {
var selectedKey: Int?
if roomsForFloor.keys.contains(String(floorBox.indexOfSelectedItem)) {
selectedKey = floorBox.indexOfSelectedItem
roomsForFloor[String(describing: selectedKey)] = numberOfRoomsTxtField.stringValue
print("\(roomsForFloor)")
for (key, value) in roomsForFloor {
print("\(key) + \(value)")
}
}
}
//MARK: - Data source
func numberOfItems(in comboBox: NSComboBox) -> Int {
return floorBoxData.count
}
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return floorBoxData[index] // give me the item in the array at the index path.
}
}
答案 0 :(得分:1)
完成它。你是对的,解决方案实际上非常简单:
let key = String(floorBox.indexOfSelectedItem)
let value = numberOfRoomsTxtField.stringValue
roomsForFloor.updateValue(value, forKey: key)
print("\(roomsForFloor)")
我从组合框中获取索引以及用户放入文本字段的内容并只添加到字典中。所以它期待一把钥匙的价值!感谢您的帮助。
答案 1 :(得分:0)
假设你的字典看起来像这样:
sys_days sd = floor<days>(datetime);
year_month_day ymd = sd;
auto tod = make_time(datetime - sd);
int y = int{ymd.year()}; // 2017
int m = unsigned{ymd.month()}; // 1
int d = unsigned{ymd.day()}; // 23
int h = tod.hours().count(); // 10
int M = tod.minutes().count(); // 4
int s = tod.seconds().count(); // 39
然后没什么可做的。您将组合连接到插座,因此您需要做的就是将其连接到IBAction,并在其内部读取其"1","10"
"2","15"
"3","15"
。由于您的stringValue
为roomsForFloor
,因此您可以通过以下方式获取客房数量:
[String:String]
我不清楚为什么你会将这些存储为字符串,这看起来很奇怪。我也不明白你对roomsForFloor的声明,你想要一组字典吗?除非我误解了这种语法,否则这没有意义。