在 UITextField 底部绘制虚线
Posted
技术标签:
【中文标题】在 UITextField 底部绘制虚线【英文标题】:Draw dotted line at bottom of UITextField 【发布时间】:2017-10-13 13:30:15 【问题描述】:我试图在 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)
得到的输出是:
预期是:
【问题讨论】:
设置shapeRect
。 height
改为 1 而不是 2?它似乎正确绘制,但在第二条点线(y)上再次绘制,偏移量会产生奇怪的结果。
【参考方案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
【讨论】:
【参考方案2】:试试这个
使用点图:
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)
【讨论】:
它将覆盖我只需要在底部的所有四个角。 哦,刚刚看到你的答案。你也做了同样的事情。伟大的。快乐编码以上是关于在 UITextField 底部绘制虚线的主要内容,如果未能解决你的问题,请参考以下文章
使用自定义 UITableViewCell 时在编辑之前更改 UITextField 文本