我有controllingView
,需要更改presentingView
中的属性。它们都在同一个ViewController
。
我可以通过presentingView
代理controllingView
让他们进行沟通。但是,如果我可以直接更改属性(),它会更加优雅和灵活
我需要实际更改presentingView
属性的属性)
我已经在这个问题中看到了它:Accessing protocol property in Swift class。
但在controllingView
中,调用delegate.propertyINeedToChange
为nil
如何从委派对象更改委托的属性?
以下是代码:
class MainViewController : UIViewController {
var controllingView = ControllingView()
let presentingView = PresentingView()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
view.addSubview(controllingView)
view.addSubview(presentingView)
self.view = view
controllingView.delegate = presentingView
}
}
class ControllingView: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
//ControlsView Setup
self.backgroundColor = UIColor(displayP3Red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0)
setupViews()
}
let testSLDR = UISlider()
var delegate: ControlsViewDelegate?
func setupViews() {
self.addSubview(testSLDR)
testSLDR.addTarget(self, action: #selector(testSLDRchanged), for: .valueChanged)
}
@objc func testSLDRchanged() {
delegate?.button?.backgroundColor = UIColor.red
}
}
class PresentingView: UIView, ControlsViewDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
let button = Button()
self.addSubview(button)
}
var button: Button?
}
protocol ControlsViewDelegate {
var button: Button? { get set }
}
class Button: UIButton { ... }
答案 0 :(得分:1)
由于视图在同一视图控制器中初始化,因此您不需要协议/委托
在ControllingView
中声明弱Button
属性
weak var presentingButton : Button?
替换该行以使用一行设置委托,将PresentingView
的按钮分配给presentingButton
属性
<击> controllingView.delegate = presentingView
击>
controllingView.presentingButton = presentingView.button
在动作中更改颜色
@objc func testSLDRchanged() {
presentingButton?.backgroundColor = UIColor.red
}