问题描述
我希望我的快速代码将所有tableview单元格加在一起,并将其从字符串转换为int。应该从确实加载func的视图中调用代码。当所有标签加在一起时,总数应为3。查看我的评论,以了解更多信息。该代码不使用情节提要。
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var numberOfRows = 3
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int { numberOfRows }
func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat { 118 }
var tableView = UITableView()
var selectedindexPath = IndexPath(row: 0,section: 0)
override func viewDidLoad() {
super.viewDidLoad()
setTableVIew()
//print the sum of the labels added togther on the tableview cells
}
func setTableVIew(){
let VCframe = view.frame
let height = VCframe.height * 0.8
let widthx = VCframe.width
tableView.frame = CGRect(x: 10,y: 0,width: widthx - 20,height: height)
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(customtv.self,forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath) as! customtv
cell.lbl.text = "\(indexPath.row)"
return cell
}
}
class customtv: UITableViewCell {
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10,y: 6,width: self.frame.width,height: 110))
view.backgroundColor = .green
print(self.frame.width)
return view
}()
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0,width: bounds.maxX,height: 110)
}
lazy var lbl : UILabel = {
let press = UILabel(frame: CGRect(x: 0,y: 3,width: 120,height: 50))
press.backgroundColor = .yellow
press.text = String("1")
return press
}()
override func setSelected(_ selected: Bool,animated: Bool) {
super.setSelected(animated,animated: true)
addSubview(backView)
backView.addSubview(lbl)
}
}
解决方法
这是您的操作方式:
override func viewDidLoad() {
super.viewDidLoad()
setTableView()
calculateSum()
}
func calculateSum() {
var sum = 0
for row in 0..<numberOfRows {
let indexPath = IndexPath(row: row,section: 0)
let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
sum += Int(cell.label.text ?? "") ?? 0
}
print(sum)
}
注意:使类和对象名称保持一致,例如:如上所述,lbl
-> label
和customtv
-> CustomTableViewCell
。甚至方法名称为setTableVIew
-> setTableView
。最好使用SwiftLint。