虚线边框不适用于 UITableview 单元格的子视图(虚线边框宽度和高度与视图不同)

dashed border not working for UITableview cell's child view(dashed border width and hight not same as the view)

在这里您可以看到 TableViewell 中的视图:

添加虚线边框的代码如下:

func addDashedBorder() 
{ 
    let color = UIColor(displayP3Red: 178.0/255.0, green: 181.0/255.0, blue: 200.0/255.0, alpha: 1.0).cgColor
    let shapeLayer:CAShapeLayer = CAShapeLayer()
    let shapeRect = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineDashPattern = [6,3]
    shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 4).cgPath
    self.layer.addSublayer(shapeLayer)
}

我在从笔尖唤醒中调用这个函数是这样的: view.addDashedBorder().

问题原因:您正在从 awakeFromNib 调用添加代码的边框。

  • 在加载 nib 时调用 Awake from,这样您的单元格将不会具有所有子视图的确切大小,当调用 awakeFromNib 时,所有视图的大小都与 nib 设计相同。所以当你设置或更新与任何视图大小相关的东西时,从笔尖醒来是错误的地方。

解决方法:正确的做法是func layoutSubviews()

  • layoutSubviews() 在任何子视图的大小将被更改或 views/subviews 的框架首次更新时被调用。

  • 这是添加边框或您的视图的正确位置,并确保它只会调用一次添加边框,因为如果任何子视图的框架发生变化,layoutSubviews 将得到多次调用。**

Reference: https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews

更简单的方法...

子类UIView,把边框相关的代码放在里面:

class DashedView: UIView {
    
    let shapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    func commonInit() -> Void {
        
        let color = UIColor(displayP3Red: 178.0/255.0, green: 181.0/255.0, blue: 200.0/255.0, alpha: 1.0).cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 2
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [6,3]
        
        layer.addSublayer(shapeLayer)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        shapeLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 4).cgPath
        
    }

}

现在您不需要 任何view.addDashedBorder() 调用。