Swift:委托协议没有正确设置UILabel

时间:2016-02-03 22:22:51

标签: ios swift protocols delegation

我有以下Protocol

protocol SoundEventDelegate{
  func eventStarted(text:String)
}

我在这堂课中打电话:

class SoundEvent {
  var text:String
  var duration:Double
  init(text: String, duration: Double){
    self.text = text
    self.duration = duration
}

var delegate : SoundEventDelegate?

func startEvent(){
    delegate?.eventStarted(self.text)

}

  func getDuration() -> Double{
    return self.duration //TODO is this common practice?
  }

} 

我的ViewController符合:

class ViewController: UIViewController, SoundEventDelegate {
  //MARK:Properties
  @IBOutlet weak var beginButton: UIButton!
  @IBOutlet weak var kleinGrossLabel: UILabel!

  override func viewDidLoad() {
     super.viewDidLoad()
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  //DELEGATE method
  func eventStarted(text:String){
    kleinGrossLabel.text = text
  }

  //MARK: actions
  @IBAction func startImprovisation(sender: UIButton) {
    var s1:Sentence = Sentence(type: "S3")
    var s2:Sentence = Sentence(type: "S1")
    var newModel = SentenceMarkov(Ult: s1, Penult: s2)
    s1.start()
    beginButton.hidden = true
  } 
}

但是,当我运行应用时,kleinGrossLabel.text不会改变。我是以错误的方式提到标签吗?或者这是我做代表团的方式不正确吗?

以下是指向ClassSentence

的完整SentenceMarkov定义的链接

https://gist.github.com/anonymous/9757d0ff00a4df7a29cb - Sentence

https://gist.github.com/anonymous/91d5d6a59b0c69cba915 - SentenceMarkov

2 个答案:

答案 0 :(得分:2)

您永远不会设置委托属性。这是零。永远不会被召唤。

答案 1 :(得分:1)

首先,在swift中安装一个setter并不常见。如果您想拥有只读属性,可以使用private(set) var propertyName 在其他情况下,只需访问评论中提到的属性

此外,我还没有看到eventArray句子[SoundEvent?]类型[SoundEvent]而非SoundEvent的原因,因为SoundEventDelegate似乎没有可用的初始值

如前所述,您不仅需要实现SoundEventDelegate协议,还需要设置委托

问题是您无法真正访问viewcontroller中的SoundEvents,因为您实例化了Sentence内的var soundEventDelegate: SoundEventDelegate?

soundEventDelegate

最简单的方法是为句子添加let s1:Sentence = Sentence(type: "S3") let s2:Sentence = Sentence(type: "S1") s1.soundEventDelegate = self s2.soundEventDelegate = self 属性并将其设置为:

soundEventDelegate

和内部声音你需要将每个事件的委托设置为Sentence的{​​{1}}

你可以这样做:

var soundEventDelegate: SoundEventDelegate? = nil {
    didSet {
        eventArray.forEach({$0.delegate = soundEventDelegate})
    }
}

或编写另一个接受委托的初始化程序

希望这会有所帮助

p.s:你不应该在快速的范围内继承NSObject,这是非常必要的