我有一套 uitableviewcell 。我想为以下条件应用边框颜色为 firstcell 应用顶部边框颜色,为 lastcell 应用底部边框颜色。
我是 swift 新手,所以我不确定这是否可能。
这是可能的。你要做的是,
UITableView
单元格,将其设置为您想要的样式。UIView
的高度1
或任何你想要的高度。让我们为它们命名topSeparator
&bottomSeparator
用于演示目的。ContentView
自定义表格视图单元格的顶部,将另一个约束到底部。Storyboards
,将topSeparator
&都连接bottomSeparator
到您的自定义单元格,disable
的topSeparator
&之后,取决于您是要以编程方式还是使用。bottomSeparator
init(frame:)
awakeFromNib()
Nibs
// Unhides top s
func showTopSeparator() {
self.topSeparator.isHidden = false
}
// Unhides bottom separator
func showBottomSeparator() {
self.bottomSeparator.isHidden = false
}
IndexPath
单元格的分隔符。见下文func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeueing custom cell
let cell = self.tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath as IndexPath) as! CustomCell
// Flag to display separators
if indexPath.row == 0 {
cell.showTopSeparator()
else if indexPath.row == data.count - 1 {
cell.showBottomSeparator()
}
return cell
}
添加Extension
.
您可以将下面的代码添加到您的ViewController
文件中,或者像我一样创建一个单独的文件。
CALayer+Extension.swift
import UIKit
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer();
switch edge {
case UIRectEdge.top:
border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: thickness)
break
case UIRectEdge.bottom:
border.frame = CGRect(x:0, y:self.frame.height - thickness, width:self.frame.width, height:thickness)
break
case UIRectEdge.left:
border.frame = CGRect(x:0, y:0, width: thickness, height: self.frame.height)
break
case UIRectEdge.right:
border.frame = CGRect(x:self.frame.width - thickness, y: 0, width: thickness, height:self.frame.height)
break
default:
break
}
border.backgroundColor = color.cgColor;
self.addSublayer(border)
}
}
TableViewController.swift
import UIKit
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let arr = ["a", "b", "c", "d"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView(frame: .zero)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as? TableViewCell else { return UITableViewCell() }
cell.label.text = arr[indexPath.row]
//Setting the border
if indexPath.row == 0 { //first cell
cell.layer.addBorder(edge: .top, color: .blue, thickness: 0.5)
}
if indexPath.row == arr.count - 1 { //last cell
cell.layer.addBorder(edge: .bottom, color: .blue, thickness: 0.5)
}
return cell
}
}
如果要删除除第一个和最后一个单元格之外的边框,可以将此属性更改为none
。