【发布时间】: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