我认为代码 sn-p 取自 https://stackoverflow.com/a/33947052/1271826,我想象一个简单的 PieView 类定义如下:
import UIKit
public class DataPoint {
let text: String
let value: Float
let color: UIColor
public init(text: String, value: Float, color: UIColor) {
self.text = text
self.value = value
self.color = color
}
}
@IBDesignable public class PieView: UIView {
public var dataPoints: [DataPoint]? { // use whatever type that makes sense for your app, though I'd suggest an array (which is ordered) rather than a dictionary (which isn't)
didSet { setNeedsDisplay() }
}
@IBInspectable public var lineWidth: CGFloat = 2 {
didSet { setNeedsDisplay() }
}
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
dataPoints = [
DataPoint(text: "foo", value: 3, color: UIColor.redColor()),
DataPoint(text: "bar", value: 4, color: UIColor.yellowColor()),
DataPoint(text: "baz", value: 5, color: UIColor.blueColor())
]
}
public override func drawRect(rect: CGRect) {
guard dataPoints != nil else {
return
}
let center = CGPoint(x: bounds.size.width / 2.0, y: bounds.size.height / 2.0)
let radius = min(bounds.size.width, bounds.size.height) / 2.0 - lineWidth
let total = dataPoints?.reduce(Float(0)) { $0 + $1.value }
var startAngle = CGFloat(-M_PI_2)
UIColor.blackColor().setStroke()
for dataPoint in dataPoints! {
let endAngle = startAngle + CGFloat(2.0 * M_PI) * CGFloat(dataPoint.value / total!)
let path = UIBezierPath()
path.moveToPoint(center)
path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.closePath()
path.lineWidth = lineWidth
dataPoint.color.setFill()
path.fill()
path.stroke()
startAngle = endAngle
}
}
public override func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
}
而且,如果您在 IB 中添加了 UIView 并将基类更改为 PieView 并添加了 @IBOutlet,那么您可以执行以下操作:
class ViewController: UIViewController {
@IBOutlet weak var pieView: PieView!
override func viewDidLoad() {
super.viewDidLoad()
pieView.dataPoints = [
DataPoint(text: "foo", value: 3, color: UIColor.redColor()),
DataPoint(text: "bar", value: 4, color: UIColor.yellowColor()),
DataPoint(text: "baz", value: 5, color: UIColor.blueColor())
]
}
}
产生:
注意,这是@IBDesignable(并实现prepareForInterfaceBuilder),因此当您将其添加到情节提要时,您会看到一个示例饼图。
显然,这是一个非常简单的实现,但您可以根据需要对其进行扩展。