在iOS中的按钮下添加虚线

时间:2017-04-10 08:53:24

标签: ios objective-c swift

我有按钮,我想在它下面添加虚线 - 所以它看起来像这样。 我知道如何使用属性字符串,但我认为我应该使用subLayers,因为我将有更多选项来配置:例如文本和行之间的距离。

enter image description here

2 个答案:

答案 0 :(得分:1)

这是如何实现的示例:

class CustomButton: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()

        layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })

        let shapeLayer = CAShapeLayer()
        shapeLayer.name = "DashedTopLine"
        shapeLayer.bounds = bounds
        shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 1
        shapeLayer.lineDashPattern = [2, 2]

        let path = CGMutablePath()
        path.move(to: CGPoint.zero)
        path.addLine(to: CGPoint(x: frame.width, y: 0))
        shapeLayer.path = path

        layer.addSublayer(shapeLayer)

    }
}

答案 1 :(得分:1)

Just set the background color for the UIImageView like this (Swift 4):

 var dottedLineView : UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFill
        view.clipsToBounds = true
        view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "dashedLine"))

        return view
    }()