在UITextField底部绘制虚线

问题描述 投票:0回答:2

我试图在UITextField的底部画一条虚线,但没有成功。以下是我到目前为止所尝试的内容。请指导。

func addDashedBorder() {


    let color = UIColor.white.cgColor
        let width = CGFloat(2.0)

        let shapeLayer:CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: frameSize.height, width: frameSize.width, height: 2.0)

        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height - width)
        shapeLayer.fillColor = UIColor.darkGray.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 2.0
       // shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPattern = [6,3]
        shapeLayer.path = UIBezierPath(rect: shapeRect).cgPath//UIBezierPath(roundedRect: shapeRect, cornerRadius: 0).cgPath

        self.layer.addSublayer(shapeLayer)
    }
}

输出结果是:enter image description here

预计是:enter image description here

ios swift core-animation dotted-line
2个回答
-1
投票

最后修好:

extension UIView {
func addDashedLine(strokeColor: UIColor, lineWidth: CGFloat) {

    backgroundColor = .clear

    let shapeLayer = CAShapeLayer()
    shapeLayer.name = "DashedTopLine"
    shapeLayer.bounds = bounds
    shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height * 1.2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = strokeColor.cgColor
    shapeLayer.lineWidth = lineWidth
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = [6, 4]

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

    layer.addSublayer(shapeLayer)
}

}

从这里得到帮助:[使用CALayer绘制虚线

] 1


-1
投票

试试这个

使用点图像:

self.textField.layer.borderWidth = 3
self.textField.layer.borderColor = (UIColor(patternImage: UIImage(named: "dot")!)).CGColor

更新:

使用以下扩展名

mytextfield.addDashedLine(strokeColor:.red,lineWidth:1)

extension UIView {
    func addDashedLine(strokeColor: UIColor, lineWidth: CGFloat) {
        backgroundColor = .clear
        let shapeLayer = CAShapeLayer()
        shapeLayer.name = "DashedTopLine"
        shapeLayer.bounds = bounds
        shapeLayer.position = CGPoint(x:30, y: 40)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPattern = [4, 4]

        let path = CGMutablePath()
        path.move(to: CGPoint.zero)
        path.addLine(to: CGPoint(x:500, y: 0))
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)
    }
}

This image shows bottom dotted line for textfield

© www.soinside.com 2019 - 2024. All rights reserved.