【问题标题】:Changing a delegate's property through protocol通过协议更改委托的属性
【发布时间】:2018-08-26 13:59:47
【问题描述】:

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

【问题讨论】:

  • 你说的是哪个属性?
  • presentingView(委托)的实例属性
  • 你想做你的定制礼物吗?
  • 请出示您的代码。
  • 如果它们都在同一个视图控制器中,为什么还要使用委托?

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


【解决方案1】:

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

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

    weak var presentingButton : Button?
    
  • 将设置委托的行替换为将PresentingView的按钮分配给presentingButton属性的行

    controllingView.delegate = presentingView

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

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

【讨论】:

  • 非常感谢。最初我无法让它工作。但我的错误是在controllingView 的初始化程序中重新声明了Button。因此留下它是button property nil
猜你喜欢
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多