swift基础学习(十一)

本文介绍了一个简单的Swift项目,演示如何使用UITableView展示带有颜色渐变效果的单元格。项目通过循环填充表格数据并设置每个单元格背景色实现渐变效果。
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

复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值