In my project I want create dashed uibutton like shown in this pricture. Is there a way I to change dashed color as well?
As the comments and answers suggest, you could use an image, but we can use a CAShapeLayer
instead and have control on every aspect.
Something like this perhaps:
class DashedButton: UIButton {
var dashedLine: CAShapeLayer!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
dashedLine = CAShapeLayer()
dashedLine.strokeColor = UIColor.white.cgColor
dashedLine.lineWidth = 4
layer.addSublayer(dashedLine)
}
override func layoutSubviews() {
super.layoutSubviews()
let path = UIBezierPath()
path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
dashedLine.lineDashPattern = [12, 7]
dashedLine.path = path.cgPath
}
}
which can be used like (note that I am using the frame here cause I tested it in a playground, a more common use would be the instantiation via a storyboard/xib file):
let button = DashedButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
button.setTitle("Forgot Password?", for: .normal)
button.dashedLine.strokeColor = UIColor.orange.cgColor
button.sizeToFit()
which produces this:
Sidenote : This example is a quick way to get you started. You could add custom setters for example to handle line coloring and patterns. Also note that I have "cheated" in a way by specifying a pattern that fills the entire width of a button ending with a dash instead of a gap, and not dynamically calculating lengths (left as an exercise for anyone that is interested in this solution :))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.