【发布时间】:2017-06-08 01:55:06
【问题描述】:
我目前正在使用字典来存储我在每个 TableView 单元格中拥有的分段控件的索引值。每个分段控件都有一个标签,对应于它所在行的索引路径。
在字典中,key是分段控件的标签(或者是分段控件所在行的索引路径,随意),value是分段控件本身的索引(即选项0对应到索引 0,选项 1 对应于索引 1)。
因此,如果有三行并且第一个分段控件选择了选项 0,第二个分段控件选择了选项 1,第三个分段控件选择了选项 1,则字典看起来像这样:
[0:0, 1:1, 2:1]
但是,这不是我得到的。当我打印字典时,其中唯一的值是我刚刚按下的按钮的键和索引。像这样的:
[0:0]
[1:1]
[2:1]
如果我按顺序为分段控件 1 选择选项 0,为分段控件 2 选择选项 1,为分段控件 3 选择选项 1。
这是我的参考代码:
import UIKit
class MyTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Sample Item"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let actionButton = YSSegmentedControl(
frame: CGRect.zero,
titles: [
"Yes",
"No"
])
actionButton.delegate = self
cell.addSubview(nameLabel)
cell.addSubview(actionButton)
actionButton.translatesAutoresizingMaskIntoConstraints = false
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-160-[v1]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel, "v1": actionButton]));
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[v0]-60-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": actionButton]))
actionButton.tag = indexPath.row
cell.backgroundColor = .green
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension MyTableViewController: YSSegmentedControlDelegate {
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) {
var indexToTag = [Int:Int]()
indexToTag[index] = segmentedControl.tag
// Looking up tag
let tag = indexToTag[index]
print("\(indexToTag)")
}
func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int) {
}
}
以及我的应用的图片:
https://i.stack.imgur.com/ezMUJ.png
谢谢, 尼克
【问题讨论】:
标签: swift dictionary memory logic