Вариант 1:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
private let drawer: DrawerProtocol = Drawer()
@IBAction func slider(_ sender: UISlider) {
label.text = String (sender.value)
let position = Int(sender.value) //тут получаем значение
drawer.setPosition(position)
}
}
import UIKit
//где-то тут надо получить значение position
class Drawer: UIView, DrawerProtocol {
private var position: Int = 0
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(2.0)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let components: [CGFloat] = [0.0, 0.0, 1.0, 1.0]
let color = CGColor(colorSpace: colorSpace, components: components)
context?.setStrokeColor(color!)
context?.move(to: CGPoint(x: 30, y: 30))
context?.addLine(to: CGPoint(x: position, y: 400))
context?.strokePath()
}
func changePosition(_ position: Int) {
self.position = position
self.setNeedsDisplay()
}
}
protocol DrawerProtocol {
func changePosition(_ position: Int)
}
Вариант 2:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
private var position: Int = 0 {
didSet{
NotificationCenter.default.post(name: Notification.Name("positionChanged"), object: nil, userInfo: ["position": position])
}
}
@IBAction func slider(_ sender: UISlider) {
label.text = String (sender.value)
self.position = Int(sender.value) //тут получаем значение
}
}
import UIKit
//где-то тут надо получить значение position
class Drawer: UIView {
private var position: Int = 0
override init(frame: CGRect) {
super.init(frame: frame)
NotificationCenter.default.addObserver(self, selector: #selector(setPosition(_:)), name: Notification.Name("positionChanged"), object: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(2.0)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let components: [CGFloat] = [0.0, 0.0, 1.0, 1.0]
let color = CGColor(colorSpace: colorSpace, components: components)
context?.setStrokeColor(color!)
context?.move(to: CGPoint(x: 30, y: 30))
context?.addLine(to: CGPoint(x: position, y: 400))
context?.strokePath()
}
@objc func setPosition(_ notification: Notification) {
if let position = notification.userInfo?["position"] as? Int {
self.position = position
self.setNeedsDisplay()
}
}
}
P.S. Не ручаюсь что второй вариант без багов, но главное это сама идея. В первом варианте класс ViewController знает про класс Drawer. во втором нет