1.这次只是一个小demo 并没有什么知识点在里面,也是跟着
"自学 iOS - 三十天三十个 Swift 项目" 做的第是一个小demo
2.效果图如下
3.代码如下
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
lazy var tableView: UITableView = UITableView()
var tableData = [String]()
let maxVaule = 20
override func viewDidLoad() {
super.viewDidLoad()
initData()
setupUI()
}
let cellID = "CELLID"
// 初始化数据
func initData() {
for i in 0...maxVaule {
tableData.append("\(i)")
}
}
// 初始化界面
private func setupUI() {
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
cell.backgroundColor = colorForIndex(index: indexPath.row)
cell.textLabel?.text = tableData[indexPath.row]
cell.textLabel?.textColor = UIColor.black
cell.selectionStyle = .none
return cell
}
// 颜色渐变
func colorForIndex(index: Int) -> UIColor {
let itemCount = tableData.count - 1
let color = (CGFloat(index))/(CGFloat(itemCount)) * 0.6
return UIColor(red: 1.0, green: color, blue: color, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
复制代码
- 其实这个主要的代码就是颜色渐变的那一块,并且设置表格
tableView.separatorStyle = .none
cell.selectionStyle = .none
复制代码