通过协议更改委托的属性

时间:2018-03-17 15:46:52

标签: ios swift model-view-controller delegates protocols

我有controllingView,需要更改presentingView中的属性。它们都在同一个ViewController

我可以通过presentingView代理controllingView让他们进行沟通。但是,如果我可以直接更改属性(),它会更加优雅和灵活 我需要实际更改presentingView属性的属性

我已经在这个问题中看到了它:Accessing protocol property in Swift class
但在controllingView中,调用delegate.propertyINeedToChangenil 如何从委派对象更改委托的属性?

以下是代码:

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 { ... }

1 个答案:

答案 0 :(得分:1)

由于视图在同一视图控制器中初始化,因此您不需要协议/委托

  • 删除协议及相关代码
  • ControllingView中声明弱Button属性

    weak var presentingButton : Button?
    
  • 替换该行以使用一行设置委托,将PresentingView的按钮分配给presentingButton属性

    <击> controllingView.delegate = presentingView

    controllingView.presentingButton = presentingView.button
    
  • 在动作中更改颜色

    @objc func testSLDRchanged() {
        presentingButton?.backgroundColor = UIColor.red
    }