Reputation: 18368
With Objective-C
, I can override the setText
function by following codes. The text
is a property of UITextField
, and I sub-class it for some custom UI design.
- (void)setText:(NSString *)text
{
[super setText:text];
....
}
My question is, how to do such thing by Swift ?
There is no such function setText
when I program with Swift. How to override the setter
and getter
methods of property with Swift ?
Upvotes: 4
Views: 10607
Reputation: 3894
In your subclass of UITextField
, override the text
property :
override public var text:String? {
didSet {
NSLog("text = \(text)")
}
}
Be careful though, this didSet
observer is called after the property was changed, so you can't decide to revert to the previous value since it's already replaced.
If you want to perform operations before the value is changed, you can use the willSet
observer, which is called before you value change.
override public var text:String? {
didSet {
NSLog("text = \(text)")
}
willSet {
NSLog("will change from \(text) to \(newValue)")
}
}
Small example with this code :
var testTextfield = MyTextFieldClass()
testTextfield.text = "test"
testTextfield.text = "test1"
And the output is
will change from Optional("") to Optional("test")
text = Optional("test")
will change from Optional("test") to Optional("test1")
Optional("test1")
Upvotes: 1
Reputation: 13181
You can use variable observers in this case.
var variableName: someType = expression {
willSet(valueName) {
// code called before the value is changed
}
didSet(valueName) {
// code called after the value is changed
}
}
A practical example.
“class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.1 Prerelease).” iBooks. https://itun.es/us/k5SW7.l
Upvotes: 2