简体   繁体   English

Swift 中的属性观察器

[英]Property Observer in Swift

Any idea how I can return a UIView from within didSet?知道如何从 didSet 中返回 UIView 吗?

I have a method that returns a UIView.我有一个返回 UIView 的方法。 I need to observe an Int and return a UIView as the Int changes.我需要观察一个 Int 并随着 Int 的变化返回一个 UIView 。 I have a didSet observer set, however, I get an error when trying to return the UIView.我有一个 didSet 观察者集,但是,在尝试返回 UIView 时出现错误。

Appreciate any help.感谢任何帮助。 Thanks.谢谢。

func newUIView() -> UIView {

   var newUIView = UIView()

   return newUIView
}

var observingValue: Int = someOtherValue {
       didSet {
             //Xcode complains whether I use return or not
            return func newUIView()          
        }
}

You say in a comment:你在评论中说:

I guess my struggle is how to observe that value and react (update UI) to it accordingly我想我的难题是如何观察该值并相应地对其做出反应(更新 UI)

An observer is a perfectly good way to do that.观察者是一个非常好的方法来做到这一点。 But you don't return something;但是你不返回任何东西; you call something.什么。 This is a very, very common pattern in Swift iOS Cocoa programming:这是 Swift iOS Cocoa 编程中非常非常常见的模式:

var myProperty : MyType {
    didSet {
        self.updateUI()
    }
}
func updateUI() {
    // update the UI based on the properties
}

At the time that the didSet code runs, myProperty has already been changed, so the method updateUI can fetch it and use it to update the interface.didSet代码运行的时候, myProperty已经改变了,所以方法updateUI可以获取它并使用它来更新界面。

What you are asking doesn't make any sense.你问的没有任何意义。

A didSet is a block of code you add to an instance variable that gets invoked when anybody changes the value of that variable. didSet 是您添加到实例变量的代码块,当任何人更改该变量的值时都会调用该代码块。 There is no place to return anything.没有地方可以退回任何东西。

If you need code that changes an instance variable and returns a view, you need to write a function:如果需要更改实例变量并返回视图的代码,则需要编写 function:

func updateObservingValue(newValue: Int) -> UIView {
   observingValue = newValue
   return newUIView()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM