【发布时间】:2020-07-29 12:23:55
【问题描述】:
我正在尝试在我的表格视图单元格的所有边上添加一个边框,我能够添加边框,但遇到了一个问题,即右侧的边框没有占据单元格的整个宽度,如截图如下。单元格边框似乎采用了故事板 UI 设置的初始宽度,例如,我已将 UI 设置为 iPhone SE,但如果我在 iPhone 11 上运行,则会出现此问题。似乎是布局未刷新的一些问题。我尝试添加 setNeedsLayout、setNeedsDisplay 和 layoutSubviews,但它们似乎都不起作用。
故事板布局
下面是完整代码
class ViewController: UIViewController {
var dataSource = [String] ()
override func viewDidLoad() {
super.viewDidLoad()
for index in 1...10 {
dataSource.append("Cell value \(index)")
}
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: MyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as? MyTableViewCell else{return UITableViewCell()}
cell.titleLabel.text = dataSource[indexPath.row]
if indexPath.row == 0 {
cell.containerView.addBorder(toEdges: [.left, .top, .right], color: .gray, thickness: 1.0)
} else if indexPath.row == dataSource.count - 1 {
cell.containerView.addBorder(toEdges: .all, color: .gray, thickness: 1.0)
} else {
cell.containerView.addBorder(toEdges: [.left, .top, .right], color: .gray, thickness: 1.0)
}
return cell
}
}
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var containerView: UIView!
}
extension UIView {
func addBorder(toEdges edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
func addBorder(toEdge edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
switch edges {
case .top:
border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
case .bottom:
border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
case .left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
case .right:
border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
default:
break
}
layer.addSublayer(border)
}
if edges.contains(.top) || edges.contains(.all) {
addBorder(toEdge: .top, color: color, thickness: thickness)
}
if edges.contains(.bottom) || edges.contains(.all) {
addBorder(toEdge: .bottom, color: color, thickness: thickness)
}
if edges.contains(.left) || edges.contains(.all) {
addBorder(toEdge: .left, color: color, thickness: thickness)
}
if edges.contains(.right) || edges.contains(.all) {
addBorder(toEdge: .right, color: color, thickness: thickness)
}
}
}
【问题讨论】:
-
刚刚复制了您的项目,粘贴了代码副本。一切正常(Xcode 11.4 / iOS 13.4),所以我假设您忘记在情节提要中添加一些约束。
-
尝试在情节提要中将视图设置为 iPhone SE 并在 iPhone 11 模拟器/设备上运行
-
Layer 不知道约束,因此您需要在布局更改时重新创建(重新构建)它们,或者只是子类化容器 UIView 并在
draw(_ rect:)中手动绘制边框(考虑到重复使用的行,对我来说,这将是更简单的方法)
标签: ios swift xcode uitableview swift4.2