【问题标题】:Dictionary only Storing One Key and Value/Overwriting Previous Key and Value仅字典存储一个键和值/覆盖以前的键和值
【发布时间】: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


    【解决方案1】:

    修订:在我看来,您在每次之前都会获得一本新字典

    indexToTag[index] = segmentedControl.tag 
    

    代码示例使用了一个变量 indexToTag,它的作用域是函数的局部变量,并且不存在。

    如果可以从函数内部移动字典(indexToTag), 但仍然在扩展中,则可以记住实例的存储属性。

    问题在于 swift 扩展不直接允许在扩展中存储属性。 (检查 Stack Overflow 中的条目以获取存储的属性和 swift 扩展)。

    挑战在于让您的代码拥有所需的类或实例变量来记住字典内容。

    这是一个使用简单扩展的沙盒示例。字典在扩展之外。

    我不知道您的代码如何最好地完成类似的事情。

    import Foundation
    
    var indexToTag = [Int:Int]()
    
    extension String {
       func control( index: Int, scTag: Int) {
          indexToTag[index] = scTag
    
          let tag = indexToTag[index]!
          print(" tag is \(tag)    indexToTag  contains: \(indexToTag)")
       }
    }
    
    let bst = String()
    
    bst.control(index: 0, scTag: 0)
    bst.control(index: 1, scTag: 1)
    bst.control(index: 2, scTag: 1)
    

    打印出来的

     tag is 0    indexToTag  contains: [0: 0]
     tag is 1    indexToTag  contains: [0: 0, 1: 1]
     tag is 1    indexToTag  contains: [2: 1, 0: 0, 1: 1]
    

    注意 indexToTag 是一个字典,因此内容没有原来的插入顺序。

    【讨论】:

    • 我该如何解决这个问题?
    • 非常感谢,我有点想多了。功能的范围是问题所在。我在扩展之外声明了字典,它工作得很好。你帮了我很大的忙,我担心我无法让它发挥作用。
    猜你喜欢
    • 2023-04-01
    • 2013-09-20
    • 1970-01-01
    • 2023-01-19
    • 2021-02-07
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多