【问题标题】:Sort cell input from customized cell in viewController从 viewController 中的自定义单元格中对单元格输入进行排序
【发布时间】:2016-10-06 11:55:10
【问题描述】:

我有一个 ViewController,其中集成了一个 tableView 和一个按钮“排序”。 此 tableView 的单元格是在另一个名为“customizedCell”的类中自定义的。

当 ViewController 被加载时,tableView 中的标签(riskTitle: UITextView! in CellCustomized)被存储在数组中的项目(RiskTitles_Plan = String in ViewController)填充。我下面的代码为此数组硬编码了一些值。

我现在要做的是将两个pickerViews生成的数字存储在标签“riskFactor:UILabel!”中在一个数组中 (RiskFactor_Plan -> RiskFactor_Int)。当用户单击按钮排序时,我的数组中的值必须进行排序,并且 tableView 中的行将以新的顺序加载(从小到大,反之亦然)。

这是我的代码(不需要的代码被删除)。

Swift 3 - 视图控制器:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var RiskTitles_Plan = [String]()
    var RiskFactor_Plan = [String]()
    var RiskFactor_Plan_Int = [Int]()

    var sortBtn = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        RiskTitles_Plan = ["my cat","my dog","my sheep","my cow","my fish"]

        sortBtn.setImage(UIImage(named: "Sort"), for: UIControlState.normal)
        sortBtn.addTarget(self, action: #selector(RiskPlan.sortAction(_:)), for: .touchUpInside)
        self.view.addSubview(sortBtn)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return RiskTitles_Plan.count
    }

 /////// Here comes the interesting part ///////

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView!.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CellCustomized

        RiskFactor_Plan.append(cell.riskFactor.text!)
        cell.riskTitle?.text = RiskTitles_Plan[indexPath.row]
        cell.backgroundColor = myColorsClass.darkCyan()

        for i in RiskFactor_Plan_Int {
            let stringItem: String = String(i)
            RiskFactor_Plan.append(stringItem)
        }

        cell.riskFactor.text! = RiskFactor_Plan[indexPath.row]

        return cell
    }

    func sortAction(_ sender:UIButton!) {

        for i in RiskFactor_Plan {
            let intItem: Int = Int(i)!
            RiskFactor_Plan_Int.append(intItem)
        }

        RiskFactor_Plan_Int = RiskFactor_Plan_Int.sorted{ $0 < $1 }
        tableView.reloadData()
    }
}

Swift 3 - CellCustomized:

import UIKit

class CellCustomized: UITableViewCell {

    var myColorsClass = myColors()
    var myStylesClass = myStyles()

    @IBOutlet weak var riskTitle: UITextView!
    @IBOutlet weak var riskFactor: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier) // the common code is executed in this super call

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()

    } // nib end

}

当点击排序按钮时,上面的代码会导致错误fatal error: unexpectedly found nil while unwrapping an Optional value for code line: let intItem: Int = Int(i)! in ViewController。

我的问题是弄清楚

  • 如何在 riskFactor: UILabel 中保存生成的值!在运行时的数组 (-> RiskTitles_Plan = String) 中。我猜每当表中的标签用生成的值更新时,都需要附加数组

  • 如何将字符串数组 (-> RiskTitles_Plan = String) 转换为整数数组 (-> RiskTitles_Plan_Int = Int)

【问题讨论】:

    标签: ios arrays swift sorting tableviewcell


    【解决方案1】:

    根据您的问题的上下文,我尝试在一个项目中复制,所以我就是这样做的,希望它可以帮助您。

    结果:

    代码:

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
      @IBOutlet weak var tableView: UITableView!
      
      var risks = Array<(title: String, factor: Int)>()
    
      override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        risks.append(("my cat", 0))
        risks.append(("my dog", 0))
        risks.append(("my sheep", 0))
        risks.append(("my cow", 0))
        risks.append(("my fish", 0))
      }
      
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return risks.count
      }
      
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        
        let riskTitle = risks[indexPath.row].title
        let riskFactor = risks[indexPath.row].factor
        
        cell.titleLabel.text = riskTitle
        cell.factorLabel.text = String(riskFactor)
        cell.index = indexPath.row
        
        
        cell.onFactorValueChanged = { [unowned self] newFactorValue, atIndex in
          self.risks[atIndex].factor = newFactorValue
        }
        
        return cell
      }
      
      @IBAction func sortRisksBasedOnFactor(_ sender: AnyObject) {
        risks.sort { (riskA, riskB) -> Bool in
          return riskA.factor > riskB.factor
        }
        
        tableView.reloadData()
      }
    }
    

    class TableViewCell: UITableViewCell {
      
      @IBOutlet weak var titleLabel: UILabel!
      @IBOutlet weak var factorLabel: UILabel!
      var index = 0
     
      var onFactorValueChanged: (Int, Int) -> Void = { _ in }
     
      @IBAction func generateFactor(_ sender: AnyObject) {
        factorLabel.text = String(random(min: 1, max: 10))
        onFactorValueChanged(Int(factorLabel.text!)!, index)
      }
      
      func random(min: Int, max: Int) -> Int {
        guard min < max else {return min}
        return Int(arc4random_uniform(UInt32(1 + max - min))) + min
      }
      
    }
    

    【讨论】:

    • 只要表只包含两个字段,这个解决方案就可以工作。这是因为排序的不是行,而是值。这导致的问题是,当我有更多字段时(例如,我的 CustomizedCell 类中也有一个 pickerView,这些字段不是排序过程的一部分,并且在按下排序按钮后表值都混在一起了。我针对我的 CustomizedCell 类中的其他字段扩展了您的示例,但是计算的标签值出现问题。也许我需要完全不同的尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多