我有一个带有自定义单元格的集合视图。当单元格在视图中居中时,我不知道如何将集合视图中的UILabel从黑色更改为红色。
发布于 2017-01-12 16:07:54
我能想到的最简单的方法是:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Cell #\(indexPath.row)"
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let tableView = scrollView as? UITableView {
for cell in tableView.visibleCells {
adjustCellColor(cell: cell)
}
}
}
func adjustCellColor(cell: UITableViewCell) {
let cellFrame = tableView.convert(cell.frame, to: view)
if cellFrame.contains(view.center) {
cell.textLabel?.textColor = UIColor.red
} else {
cell.textLabel?.textColor = UIColor.black
}
}
}
请记住,UITableView
是UIScrollView
的子类( UITableViewDelegate
协议继承自UIScrollViewDelegate
协议),所以当视图控制器是UITableView
的委托时,可以实现func scrollViewDidScroll(_ scrollView: UIScrollView)
之类的UIScrollViewDelegate
方法。在滚动表视图时调用此方法。它遍历所有可见单元格,如果单元格位于视图的中心,则将文本颜色设置为红色,否则设置为黑色。
https://stackoverflow.com/questions/41615657
复制相似问题