我想在表格 View 中显示这个循环的所有值。该代码用于计算贷款的摊销表。我尝试将循环的数据保存在数组中,但它总是给我最后的值。我真的被困在这上面了。那我该怎么做呢?这是我的代码:
import UIKit
class tableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var arr = [Int]()
var cell:tableCell!
var TPayment: float_t! // calls value of 59600 from main controller
var years1: float_t! // number of months = 180 ( 15 years)
var monthlyPayment: float_t! // 471
var interest: float_t! // 5%
var principil: float_t! //222
var interestrate: float_t! // 249
var initil: float_t!
var data = Array<float_t>()
var data2: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let c = Int(years1)
arr += 0...c
tableCalculation()
// Register custom cell
let nib = UINib(nibName: "table", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
func tableCalculation() {
let years = Int(years1)
initil = TPayment - 0
for i in 0..<years {
initil = initil - principil
interest = initil * interestrate
principil = monthlyPayment - interest
print("Month : \(monthlyPayment), principil: \(principil),interest: \(interest), initi: \(initil)")
data = [interest]
self.data2 = [initil]
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! tableCell
cell.lbl1.text = "\(arr[indexPath.row])"
cell.lbl2.text = "\(monthlyPayment)"
cell.lbl3.text = "\(data[indexPath.row % data.count])"
cell.lbl4.text = "\(principal)"
cell.lbl5.text = "\(self.data2[indexPath.section])"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Row \(indexPath.row) selected")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40
}
}
最佳答案
主要问题在于您的数据数组。
在填充数据数组的循环中,在 tableCalculation
中,有这个:
data = [interest]
这意味着对于每次迭代,您将数据数组设置为[interest]
,而不是将新项目添加到数组。
你应该怎么做:
data.append(interest)
请注意,您在 self.data2
中犯了同样的错误。但现在您知道如何修复此类错误了。
关于ios - UITableView 显示循环的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36248694/