Swift: 在 table 视图单元格的一侧添加边框

Swift: Add border to one side of a table View cell

如何在 table 视图中的自定义单元格右侧添加灰色边框颜色? 我有一个 table 的自定义单元格,想为所有单元格添加边框颜色,但在右侧仅表示可以向右滑动, 这是我的自定义单元格 class:

import UIKit

class AdminCustomCell: UITableViewCell {


@IBOutlet weak var MainView: UIView!
@IBOutlet weak var BackView: UIView!

@IBOutlet weak var Km: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()

    self.BackView.layer.borderWidth = 1
    self.BackView.layer.cornerRadius = 20
    self.BackView.layer.borderColor = UIColor.white.cgColor
    self.BackView.layer.masksToBounds = true

    self.MainView.layer.shadowOpacity = 0.18
    self.MainView.layer.shadowOffset = CGSize(width: 0, height: 2)
    self.MainView.layer.shadowRadius = 6
    self.MainView.layer.shadowColor = UIColor.black.cgColor
    self.MainView.layer.masksToBounds = false
}

//@IBOutlet weak var ParkingView: UIView!
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var Alert: UILabel!
@IBOutlet weak var Logos: UIImageView!
@IBOutlet weak var ParkingView: UIView!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}


override func layoutSubviews() {
    super.layoutSubviews()

    ParkingView.frame = ParkingView.frame.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
}

}

您可以尝试使用 CALayer 或覆盖 drawRect 并在您想要的地方画一条线。

这里是一个使用 CALayer 的例子

private func addRightBorder() {
    let border = CALayer()
    
    let borderWidth: CGFloat = 5
    
    // Set the color your want
    border.backgroundColor = UIColor.red.cgColor
    
    // Create a rect only on the right of the view
    border.frame = CGRect(x: bounds.maxX - borderWidth,
                          y: 0,
                          width: borderWidth,
                          height: bounds.maxY)
    
    layer.addSublayer(border)
}

更新

基于 Duncan 的有效评论:

Note that if your app supports device rotation (or iPad multitasking), you need to add logic that detects layout changes and moves the border layer. Thus for a full implementation you'll probably need to save the border layer as an instance var and add code to adjust its position on layout changes.

以下是一些有望解决这种情况的更改:

// Persist the CALayer
var rightBorder: CALayer?

let borderWidth: CGFloat = 5

override func layoutSubviews() {
    super.layoutSubviews()
    
    // Add right border if we haven't already
    if rightBorder == nil {
        addRightBorder()
    }
    
    // Update the frames based on the current bounds
    rightBorder?.frame = CGRect(x: bounds.maxX - borderWidth,
                                y: 0,
                                width: borderWidth,
                                height: bounds.maxY)
}

private func addRightBorder() {
    rightBorder = CALayer()
    
    rightBorder!.backgroundColor = UIColor.red.cgColor
    
    layer.addSublayer(rightBorder!)
}