我创建了一个 Profile 类,我正试图让这个 viewcontroller 从用户提供的信息中保存计费配置文件对象,然后将这些配置文件显示在 TableView 中的列表中,用户提供的名称下。我已经用数组尝试过这个,但决定放弃它,因为字典看起来更合理,因为我可以将配置文件名称作为键。并将其显示在表格中
但是,我在用配置文件填充表格时遇到了问题。
非常感谢任何帮助,我愿意尝试任何建议。我会提供图片和代码
var dictionary = [String:Profile]()
let profile1 = Profile()
profile1.firstNameB = firstNameBill
profile1.lastNameB = lastNameBill
profile1.emailB = emailBill
profile1.phoneB = phoneBill
profile1.address1B = address1Bill
profile1.address2B = address2Bill
profile1.zipB = zipBill
profile1.cityB = cityBill
profile1.firstNameS = firstNameShip
profile1.lastNameS = lastNameShip
profile1.phoneS = phoneShip
profile1.address1S = address1Ship
profile1.address2S = address2Ship
profile1.zipS = zipShip
profile1.cityS = cityShip
dictionary.updateValue(profile1, forKey: pName)
}
更新:仍然有点困惑,我用以下代码创建了一个新文件并得到了它。
class ProfileTable: NSViewController {
@IBOutlet weak var tableView: NSTableView!
var profiles: [String: Profile] = [:]
var indices: [String] = []
override func viewDidLoad() {
indices = profiles.keys.sorted()
}
}
extension ProfileTable: NSTableViewDataSource {
func tableView(_ tableView: NSTableView, numberOfRowsInSection section: Int) -> Int {
return indices.count
}
func tableView(_ tableView: NSTableView, cellForRowAt indexPath: IndexPath) -> NSTableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MyCell.self), for: indexPath) as MyCell
cell.profile = profiles[indices[indexPath.row]]!
return cell
}
}
最佳答案
你可以做的是使用一个数组来索引你的字典。您可以从字典的键数组属性生成数组。在这里我按键排序,但您可能应该提供一个闭包以按配置文件名称或其他一些更有意义的字段排序。
class V: UIViewController {
@IBOutlet weak var tableView: UITableView!
var profiles: [String: Profile] = [:]
var indices: [String] = []
override func viewDidLoad() {
indices = profiles.keys.sorted()
}
}
extension V: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return indices.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MyCell.self), for: indexPath) as MyCell
cell.profile = profiles[indicies[indexPath.row]]!
return cell
}
}
关于Swift 3 从字典中填充 TableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43444532/