使用UIKit很容易绘制虚线线条。所以:在2017年使用IBDesignable绘制虚线(不是虚线!)线条
CGFloat dashes[] = {4, 2};
[path setLineDash:dashes count:2 phase:0];
[path stroke];
有没有什么办法的方式来画一个真正的虚线?
任何想法?
由于这个问题是真的老了,没有人置于满@IBDesignable
的解决方案,这是...
希望这样可以节省别人打字。
@IBDesignable class DottedVertical: UIView {
@IBInspectable var dotColor: UIColor = UIColor.etc
@IBInspectable var lowerHalfOnly: Bool = false
override func draw(_ rect: CGRect) {
// say you want 8 dots, with perfect fenceposting:
let totalCount = 8 + 8 - 1
let fullHeight = bounds.size.height
let width = bounds.size.width
let itemLength = fullHeight/CGFloat(totalCount)
let path = UIBezierPath()
let beginFromTop = CGFloat(0.0)
let top = CGPoint(x: width/2, y: beginFromTop)
let bottom = CGPoint(x: width/2, y: fullHeight)
path.move(to: top)
path.addLine(to: bottom)
path.lineWidth = width
let dashes: [CGFloat] = [itemLength, itemLength]
path.setLineDash(dashes, count: dashes.count, phase: 0)
// for ROUNDED dots, simply change to....
//let dashes: [CGFloat] = [0.0, itemLength * 2.0]
//path.lineCapStyle = CGLineCap.round
dotColor.setStroke()
path.stroke()
}
}
我把它做成垂直的,你可以很容易地改变。
只要把一个UIView场景;无论你希望的宽度如何,这将是虚线的宽度。
只需将类更改为DottedVertical
即可。它将在故事板中正确渲染。
注意,对于块(“TOTALCOUNT”等等...)导致完全的块,所述像素的高度给出的示例代码,与所述的UIView的端部匹配的正在创造这条线。
一定要勾选RobMayoff的答案,下面给出了点不是块的两行代码。
这里的画斜线一个很好的方式! :) https://stackoverflow.com/a/45228178/294884 – Fattie 2018-02-13 14:07:27