[英]How can I call a function only after all properties have been set in my UIView subclass?
I have a UIView subclass somewhat like this:我有一个 UIView 子类,有点像这样:
class AView: UIView {
var aString = "A String"
var aBool = true
override func didMoveToSuperview() {
func doSomethingWithTheString() {
if aBool {
doSomething(withString: aString)
}
}
}
}
Then I add a UIView to a storyboard and set it's class as AView
.然后我将一个 UIView 添加到故事板并将它的类设置为
AView
。 I link it to my view controller and do this:我将它链接到我的视图控制器并执行以下操作:
@IBOutlet weak var aView: AView!
override func viewDidLoad() {
aView.aBool = false
aView.aString = "Another String"
}
The thing is, when doSomethingWithTheString()
is called aBool
is still true
and aString is still "A String"
, even though I changed them at viewDidLoad()
.问题是,当
doSomethingWithTheString()
被调用时aBool
仍然是true
并且 aString 仍然是"A String"
,即使我在viewDidLoad()
更改了它们。
So is there somewhere in AView
where I can put doSomethingWithTheString()
for it to be called only when all properties have been set?那么在
AView
中是否有某个地方可以放置doSomethingWithTheString()
以便仅在设置所有属性时才调用它? I hoped didMoveToSuperview()
would do the trick, but apparently it's still too early.我希望
didMoveToSuperview()
能解决问题,但显然现在还为时过早。
I thought of calling it in a property's setter, but I don't know which properties will be set and which will be left with their default, and it should only be called when the last property has been set.我想在属性的 setter 中调用它,但我不知道将设置哪些属性,哪些将保留默认值,并且只能在设置最后一个属性时调用它。
Put aString and aBool in a dictionary (aDictionary) then declare将 aString 和 aBool 放入字典(aDictionary)中,然后声明
var aDictionary: NSDictionary? {
didSet{
doSomethingWithTheString()
}
}
Of course change a bit the doSomethingWithTheString() to work with the dictionary当然改变一下 doSomethingWithTheString() 来处理字典
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.