Draw dotted (not dashed!) line, with IBDesignable in 2017

前端 未结 10 1716
死守一世寂寞
死守一世寂寞 2020-11-28 03:25

It\'s easy to draw a dashed line with UIKit. So:

CGFloat dashes[] = {4, 2};
[path setLineDash:dashes count:2 phase:0];
[path stroke];
         


        
10条回答
  •  伪装坚强ぢ
    2020-11-28 04:18

    Using a UIView extension, compatible with Swift 3.0 the following should work:

    extension UIView {
    
        func addDashedBorder(strokeColor: UIColor, lineWidth: CGFloat) {
            self.layoutIfNeeded()
            let strokeColor = strokeColor.cgColor
    
            let shapeLayer:CAShapeLayer = CAShapeLayer()
            let frameSize = self.frame.size
            let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
    
            shapeLayer.bounds = shapeRect
            shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeColor = strokeColor
            shapeLayer.lineWidth = lineWidth
            shapeLayer.lineJoin = kCALineJoinRound
    
            shapeLayer.lineDashPattern = [5,5] // adjust to your liking
            shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: shapeRect.width, height: shapeRect.height), cornerRadius: self.layer.cornerRadius).cgPath
    
            self.layer.addSublayer(shapeLayer)
        }
    
    }
    

    Then in a function that runs after viewDidLoad, like viewDidLayoutSubviews, run the addDashedBorder function on the view in question:

    class ViewController: UIViewController {
    
        var someView: UIView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            someView = UIView()
            someView.layer.cornerRadius = 5.0
    
            view.addSubview(someView)
    
            someView.translatesAutoresizingMaskIntoConstraints = false
            someView.widthAnchor.constraint(equalToConstant: 200).isActive = true
            someView.heightAnchor.constraint(equalToConstant: 200).isActive = true
            someView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
            someView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        }
    
        override func viewDidLayoutSubviews() {
            someView.addDashedBorder(strokeColor: UIColor.red, lineWidth: 1.0)
        }
    
    }
    

提交回复
热议问题