Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField `setText` in Swift

Tags:

ios

swift

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 ?

like image 579
AechoLiu Avatar asked Sep 16 '25 12:09

AechoLiu


1 Answers

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

like image 71
Tommie C. Avatar answered Sep 18 '25 10:09

Tommie C.