1

I have button and I want to add dashed line under it - so it will look like this. I know how to do it with attributed strings but I think that I should use subLayers because I will have more options to configure: such as distance between text and line.

enter image description here

moonvader
  • 19,761
  • 18
  • 67
  • 116
  • [check out this user's extension - looks like what you need](http://stackoverflow.com/a/38194152/5143364) – PiKey Apr 10 '17 at 09:05

2 Answers2

1

This is example how it is possible to achieve:

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)

    }
}
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • This will keep adding a layer everytime `layoutSubviews` is called. You will have to set a unique identifier and search for the layer and just remake its path if the layer exists. – Rikh Apr 10 '17 at 09:16
  • To change top border to bottom - maybe code should be changed to path.move(to: CGPoint(x:0, y: frame.height)) path.addLine(to: CGPoint(x: frame.width, y: frame.height)) – moonvader Apr 10 '17 at 09:47
  • Given `-layoutSubviews`'s docs say this method is for "laying out and resizing subviews", I'm not sure it's a good idea to change the layer hierarchy from inside this method. You should probably create the layer (and maybe hide it) in `-initWithFrame:`/`-initWithCoder:` and then only resize it here. – uliwitness Apr 10 '17 at 10:07
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
    }()