首先创建一个cocoa class 继承自NSView 不是为view 关连一个文件 是再创建一个文件
在progressControl中 代码是这样的 实现一个progressControl
import UIKit class progressControl: UIView { //自定义一个属性 用来改变填充的值 private var _progressValue:CGFloat = 0 //设置和获取 set和get public func getProgressValue() ->CGFloat { return _progressValue } public func setProgressValue(value:CGFloat) { _progressValue = value //要进行重绘 所以要调用这个函数 setNeedsDisplay() } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { //重绘的代码 var ctx = UIGraphicsGetCurrentContext() //获取到当前的半径 var r = rect.width / 2 //绘制背景 CGContextAddArc(ctx, r, r, 0, 0, 3.1415926 * 2 * _progressValue, 0) CGContextSetRGBFillColor(ctx, 0.7, 0.7, 0.7, 1) CGContextFillPath(ctx) CGContextAddArc(ctx, r, r, r, 0, 3.1415926 * 2 * _progressValue, 1) //设置颜色 为蓝色 CGContextSetRGBFillColor(ctx, 0, 0, 1, 1) CGContextFillPath(ctx) } }随后在view controller中实现这个自定义的控件 并进行添加 用progressControll 来进行创建 因为文件名是这个
import UIKit class ViewController: UIViewController { //创建progressControll实例 @IBAction func change(sender: UISlider) { pc.setProgressValue(CGFloat(sender.value)) } var pc = progressControl() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //创建progressControll实例 pc = progressControl(frame: CGRect(x: 20,y: 20,width: 100,height: 100)) self.view.addSubview(pc) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }接着拖进一个slider 并连接在view controller中
import UIKit class ViewController: UIViewController { //创建progressControll实例 @IBOutlet var slider: UISlider! @IBAction func change(sender: UISlider) { pc.setProgressValue(CGFloat(sender.value)) slider.minimumValue = 0 slider.maximumValue = 1 } var pc = progressControl() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. slider.minimumValue = 0 slider.maximumValue = 1 //创建progressControll实例 pc = progressControl(frame: CGRect(x: 20,y: 20,width: 100,height: 100)) self.view.addSubview(pc) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }